Reputation: 153
I need to add data to two separate columns in a datagrid by referring two separate text files for each of them. The two columns are called MACAddress and TxPower. the resulting datagrid should provide TxPower in front of the related MACAddress. But currently i'm receiving MACAddress and TxPower in separate rows.
I know how to get the Txpower for the corresponding MACAddress by referring a single text file. But here the difficulty that i undergo is the usage of two separate text files to obtain the table. Please help. thanks in advance
the coding that i use is given below:
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);
}
Upvotes: 1
Views: 76
Reputation: 88044
The code you showed creates a new row for each record found in both the first and second data files.
What you should probably do is create the rows based on the first data file. Then, during processing the second file, look up the key in the table to get the row to modify.
You will probably need to create a primary key for the original data table. For example (this goes immediately after your table creation):
DataColumn[] keys = new DataColumn[1];
keys[0] = dtt.Columns["MacAddress"];
dtt.PrimaryKey = keys;
Then while loading the second data file do something like:
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;
Note you should only assign the data source AFTER the table has been built. There is no point in assigning it for each line that was read.
http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.100).aspx
Upvotes: 1