GST Billing Software

header image

Preferred Settings in Dialog Box

Erachana Line

47. How to add rows to DataGrid?


When you need to add your own data rows, to data grid at runtime, you can use the following code

DateTime myDate = DateTime.Now;

DataTable dtVals = (DataTable) dgrData.DataSource;

for (int i = 1; i <= 5; i++)

{

if (i > 1)

{ myDate= myDate.AddMonths(1);}

DataRow dr = dtVals.NewRow();

dr[0] = myDate.Month;

dr[1] = myDate.ToString("MMMM") + " / " + myDate.Year;

dr[2] = myDate.Year;

dr[3] = DBNull.Value;

dtMonths.Rows.Add(dr);

}

dgrData.DataSource= dtVals;

In the above code, the DataGrid has 4 columns,

1. Month (Data Type – Integer)

2. Month Name (Data Type – String)

3. Year (Data Type – Integer)

4. Remarks (Data Type – String)

The first 3 columns have the property Allow Null = false. And Column 4 has Allow Null = True. Hence, we have given DBNull.Value for the Null Value.

Note : The following things have to be taken care of, while adding row –

1. Data type of the data

2. If data is null

3. Format of the Data