2012-02-08 60 views
1

我需要通過爲每個數據網格引用兩個單獨的文本文件來將數據添加到數據網格中的兩個單獨列。這兩列稱爲MACAddress和TxPower。產生的數據網格應該在相關的MAC地址前面提供TxPower。但目前我在單獨的行中接收MACAddress和TxPower。將數據插入數據網格中的行中的問題

我知道如何通過引用單個文本文件來獲取相應MAC地址的Txpower。但是,這裏我遇到的困難是使用兩個單獨的文本文件來獲取表格。請幫忙。在此先感謝

,我使用的編碼下面給出:

DataTable dtt = new DataTable(); 
dtt.Columns.Add("MACAddress", typeof(string)); 
dtt.Columns.Add("TxPower", typeof(string)); 

try 
{ 
using (System.IO.StreamReader sr = new System.IO.StreamReader(textBox1.Text.Replace("'\'", "'\\'"))) 
    { 
string line, mac; 
while ((line = sr.ReadLine()) != null) 
     { 
DataRow DTR = dtt.NewRow(); 
DTR["MACAddress"] = mac; 
dtt.Rows.Add(DTR); 
dataGridView1.DataSource = dtt; 
     } 
    } 
} 
catch (Exception exp) 
{ 
MessageBox.Show(exp.Message); 
} 




try 
{ 
using (System.IO.StreamReader sr = new System.IO.StreamReader(textBox2.Text.Replace("'\'", "'\\'"))) 
    { 
string line; 
while ((line = sr.ReadLine()) != null) 
     { 

DataRow DTR=dtt.NewRow(); 
DTR["TxPower"] = line.Substring(78, 4); 
dtt.Rows.Add(DTR); 
dataGridView1.DataSource = dtt; 
     } 
    } 
} 
catch (Exception exp) 
{ 

    MessageBox.Show(exp.Message); 
} 

回答

1

您顯示的代碼在第一和第二個數據文件中找到的每個記錄創建一個新行。

你應該做的可能是根據第一個數據文件創建行。然後,在處理第二個文件的過程中,查看錶格中的鍵以獲取要修改的行。

您可能需要爲原始數據表創建primary key。例如(這會立即轉到你的表創建後)

DataColumn[] keys = new DataColumn[1]; 
keys[0] = dtt.Columns["MacAddress"]; 
dtt.PrimaryKey = keys; 

然後同時加載第二個數據文件做這樣的事情:

using (System.IO.StreamReader sr = new System.IO.StreamReader(textBox2.Text.Replace("'\'", "'\\'"))) 
{ 
    string line; 
    string macAddress; 
    while ((line = sr.ReadLine()) != null) 
    { 
     macAddress = line.Substring(?,?) // get the macAddress from the loaded line here. 
      // you will need to replace the ?,? with the actual position info for that field. 
     DataRow row = dtt.Rows.Find(macAddress); 
     if (row != null) { 
      row["TxPower"] = line.Substring(78, 4); 
     } 
    } 
} 
dataGridView1.DataSource = dtt; 

注意你應該只指定數據源後,將表已經建成。爲讀取的每一行分配它沒有意義。

http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.100).aspx

+0

是的。這正是我想要的。謝謝 – 2012-02-09 11:57:27