Search code examples
c#gridviewdesktop-applicationassigndatagridviewtextboxcell

How to assign value to the datagridviewtextboxcolumn in code behind?


I have a gridview of type datagridviewtextbox column.

It has following fields.

SrNo.    | Description    | HSN Code    | Qty   | Rate   | Amount 

I have fetched records of "Description", "HSN Code" , "Qty" & "Rate" in the dataset.

I Want to generate the "SrNo" and "Amount" in my program.

My code is:

int i=0;
ds = new DataSet();
ds = db.getDetailRecords(Convert.ToInt32(txtBillNo.Text));


for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
     grdData.Rows[i].Cells[0].Value = i;
     grdData.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["Description"].ToString();
     grdData.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["HSNCode"].ToString();
     grdData.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["Qty"].ToString();
     grdData.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["Rate"].ToString();
     grdData.Rows[i].Cells[5].Value = Convert.ToDouble(ds.Tables[0].Rows[i]["Qty"]) * Convert.ToDouble(ds.Tables[0].Rows[i]["Rate"]);                        
}

But it's not working. It gives the error that Index was out of Range.

How do I assign the dataset values to the grid? Please help.


Solution

  • I guess you skipped the DataBinding to GridView:

    int i=0;
    ds = new DataSet();
    ds = db.getDetailRecords(Convert.ToInt32(txtBillNo.Text));
    grdData.DataSource = ds.Tables[0]; // you skipped this