テキストファイルの読み方などのトピックがたくさんあり、すべて読んだような気がします。しかし、私はそれを私の問題に適用することができませんでした。
次のようなテキストファイルがあります。
ProductID,Product,CustomerID,lineone,linetwo,linethree AABBCC,バナナ,K001,something,something,something BBCCAA,りんご,K002,something1,something2,something3 AACCBB,オレンジ,K003,something4,something5,something6 CCAABB,バナナ,K001,何か、何か、何か
textbox(tbCustomerID) と dataGridView (dgvProducts) があるフォーム (Form1) があります。
私がやりたいことは、Form1 のテキスト ボックスに CustomerID を入力したいということです。次に、テキスト ファイルにあるすべての CostumerID をループして、事前定義された 6 列の dataGridView に ProductID と Product を表示します。(ProductID と Product = 列 1 と 2)
私の最初の試み:(通常のクラスから)
public DataTable ReadFromFile()
{
//Read the data from text file
string[] textData = File.ReadAllLines("MyTextFile.txt");
string[] headers = textData[0].Split(',');
//Create and populate DataTable
DataTable dataTable1 = new DataTable();
foreach (string header in headers)
dataTable1.Columns.Add(header, typeof(string), null);
for (int i = 1; i < textData.Length; i++)
dataTable1.Rows.Add(textData[i].Split(','));
return dataTable1;
}
次に、私の Form1 で:
Form1 frm1 = new Form1();
private void button_Click(object sender, EventArgs e)
{
dgvProducts.DataSource = frm1.ReadFromFile();
}
しかし、これはテキストファイルのすべてのアイテムをdataGridViewに表示しただけです。
試行 2: (私のクラスから)
public string findCustomer(string CustomerID)
{
StreamReader sr = new StreamReader("MyTextFile.txt");
string searchId = CustomerID;
string actualId = "";
string produktID = "No match found";
string[] details = null;
string line = null;
while ((line = sr.ReadLine()) != null)
{
line = line.Trim();
if (line == "") continue;
details = line.Split(',');
actualId = (details[0]);
if (actualId == searchId)
{
productID = details[2].Replace("\"", "");
break;
}
}
sr.Close();
return productID;
}
次にForm1で
Form1 frm1 = new Form1();
private void button_Click(object sender, EventArgs e)
{
string aa = tbKundID.Text;
dgvProducts.Rows.Add(frm1.findCustomer(aa));
}
しかし、この方法では、テキストファイルの列 2 から 1 つの値しか取得できません。これは、C# で 2 つの値を返すことができないためです。また、テキストファイルからすべての行を読み取ってから、すべての列を分割して、表示したい特定のものを何とか表示しようとしましたが、検索でもdataGridViewへの追加でもそれを機能させることができませんでした..これは私の最後の手段なので、可能な限り簡単な方法でそれを行う方法について助けていただければ幸いです.