C# 向datagrid中的行插入数据时出现问题
我需要通过为每个列引用两个单独的文本文件,将数据添加到datagrid中的两个单独的列中。这两列分别称为MACAddress和TxPower。生成的datagrid应该在相关MACAddress前面提供TxPower。但目前我收到的MACAddress和TxPower是分开的两行 我知道如何通过引用单个文本文件获得相应MACAddress的Txpower。但在这里,我遇到的困难是使用两个单独的文本文件来获取表。请帮忙。提前谢谢 我使用的编码如下所示:C# 向datagrid中的行插入数据时出现问题,c#,C#,我需要通过为每个列引用两个单独的文本文件,将数据添加到datagrid中的两个单独的列中。这两列分别称为MACAddress和TxPower。生成的datagrid应该在相关MACAddress前面提供TxPower。但目前我收到的MACAddress和TxPower是分开的两行 我知道如何通过引用单个文本文件获得相应MACAddress的Txpower。但在这里,我遇到的困难是使用两个单独的文本文件来获取表。请帮忙。提前谢谢 我使用的编码如下所示: DataTable dtt = new Da
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);
}
显示的代码为在第一个和第二个数据文件中找到的每个记录创建一个新行 您可能应该做的是基于第一个数据文件创建行。然后,在处理第二个文件的过程中,在表中查找键以获取要修改的行 您可能需要为原始数据表创建一个。例如(这将在创建表之后立即执行): 然后在加载第二个数据文件时执行以下操作:
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;
注意,您只应在生成表后分配数据源。为读取的每一行分配数据源没有意义
显示的代码为在第一个和第二个数据文件中找到的每条记录创建新行 您可能应该做的是基于第一个数据文件创建行。然后,在处理第二个文件的过程中,在表中查找键以获取要修改的行 您可能需要为原始数据表创建一个。例如(这将在创建表之后立即执行): 然后在加载第二个数据文件时执行以下操作:
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;
注意,您只应在生成表后分配数据源。为读取的每一行分配数据源没有意义