Reputation: 6918
I am getting some data in unstructured form. So i want it to be in structured form. So i take datatable in this i have added two columns, i.e. "field" and "value". Now i added first row in data along with the data in these two columns. But the prob is its replacing the old data every time i come again to save the data in this datatable. My code is:
DataTable dt = new DataTable();
dt.Columns.Add("Field", typeof(string));
dt.Columns.Add("Value", typeof(string));
dt.Rows.Add(val.Substring(0, val.IndexOf(":") + 1), val.Substring(val.IndexOf(":") + 1, val.Length - val.IndexOf(":") - 1))
Upvotes: 0
Views: 2270
Reputation: 30666
Using DataTable, you have to create a new row before adding it:
DataTable dt = new DataTable();
dt.Columns.Add("Field", typeof(string));
dt.Columns.Add("Value", typeof(string));
var row = dt.NewRow();
dt["Field"] = "FieldName";
dt["Value"] = "Value";
dt.Rows.Add(row);
You must use the NewRow method to create new DataRow objects with the same schema as the DataTable. After creating a DataRow, you can add it to the DataRowCollection, through the DataTable object's Rows property. When you use NewRow to create new rows, the rows must be added to or deleted from the data table before you call Clear.
But if you are only handling a key/value pair, why don't you use a Dictionary<string, string>
?
Upvotes: 1
Reputation: 1747
Are u using this in a loop? only the last line should be in the loop otherwise youre instantiating the datatable each loop.
Upvotes: 0