Anuya
Anuya

Reputation: 8350

Assign value to a specific Column in Datatable using c#

I have created a datatable and added many columns to it.

When the datatable is empty, i want to assign a value to a specific column.

Like finding the column name in datatable and assign value to it... Is it possible ? Thanks

        dt_FAQ.Columns.Add("FQ_Question_1", typeof(string));
        dt_FAQ.Columns.Add("FQ_Answer_1", typeof(string));
        dt_FAQ.Columns.Add("FQ_Question_2", typeof(string));
        dt_FAQ.Columns.Add("FQ_Answer_2", typeof(string));
        dt_FAQ.Columns.Add("FQ_Question_3", typeof(string));
        dt_FAQ.Columns.Add("FQ_Answer_3", typeof(string));
        dt_FAQ.Columns.Add("FQ_Question_4", typeof(string));
        dt_FAQ.Columns.Add("FQ_Answer_4", typeof(string));
        dt_FAQ.Columns.Add("FQ_Question_5", typeof(string));
        dt_FAQ.Columns.Add("FQ_Answer_5", typeof(string));

There is a scenario where i would get only the value that has to be assigned to column "FQ_Answer_1" in the above datatable. In that case, i want to assgn value to that column alone and pass empty string "" to other columns. Possible ?

Upvotes: 4

Views: 53967

Answers (2)

Habib
Habib

Reputation: 223392

In case of your existing datatable with data inside, you have to iterate through the datatable rows and set values to each column

foreach(DataRow dr in dt_FAQ.Rows)
{
     dr["FQ_Answer_1"] = "your value";
     dr["FQ_Question_1"] = string.Empty;
     dr["FQ_Question_2"] = string.Empty;
     //.... for all the columns
}

To find a particular column you can do:

    DataColumn dc = dt.Columns.Cast<DataColumn>().Where(r => r.ColumnName == "yourname").FirstOrDefault();
   //Or simpler 
    DataColumn dc2 = dt.Columns["yourcol"];

EDIT: For new Row:

DataRow dr = dt_FAQ.NewRow();
dr["FQ_Answer_1"] = "some value";
dt_FAQ.Rows.Add(dr);

This will create a new row with "some value" for column FQ_Answer1, all the other remaining columns will have string.Empty as default value.

You can check other columns like:

string test = dt_FAQ.Rows[0]["FQ_Question_1"].ToString();

Here test will contain an empty string.

Upvotes: 7

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48590

How about

 DataRow dr = mydatatable.NewRow();

 dr[0] = 1;                // Assuming that first column is int type
 dr[0] = "someothervalue"; //Assuming that second column is string type
 ..
 ..
 ..
 .. // Repeat for other columns.
 mydatatable.AddRow(dr);

Upvotes: 0

Related Questions