C# .NET - how to add new row in datagrid view - Asked By JAYA PRAKASH on 20-Mar-13 01:10 AM


Iam retrieving record from table and adding to the datagridview. When i select another record, the reterived record must be added to the next row.
Here's my code.
con = new SqlConnection("Data Source=(local);Initial Catalog=Pharmaceuticals;Integrated Security=True");
con.Open();
             SqlCommand sqlCmd = new SqlCommand();


            sqlCmd.Connection = con;
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "select * from Product_Details where Item='" + item_combo.Text + "'";


            SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);


            DataTable dtRecord = new DataTable();
            sqlDataAdap.Fill(dtRecord);
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = dtRecord;
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            DataTable dt=new DataTable();
            DataRow dr = dt.NewRow();
            dt.Rows.Add(dr); 
             
            con.Close();

Tom Wilson replied to JAYA PRAKASH on 20-Mar-13 12:10 PM
Try this code:
DataTable dt;
 DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
 

if (dt == null)

{

dt = dtrecord.Copy();

}


else

{

DataRow nr = dtrecord.NewRow();

for (int counter = 0; counter < dtrecord.Columns.Count; counter++)

{

nr[counter] = dtrecord.Rows[0][counter];

}

dt.Rows.Add(nr);

}
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);