2012-02-08 41 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