user2936286 user2936286 - 2 months ago 9
C# Question

DataGridView Doesn't show the dataTable that binded to it

I have a DataGridView in my project that working as my basket in the shop. When I select a commodity in my main DataGridView, the information of that commodity selected from my database and added to a DataTable object and the end my data table bound to my basketDataGridView, but in my project my basketDataGridView doesn't show the content of my dataTable.

You can see the below code.

Note: my

FrooshDataGridview
is my main Datagridview and the
nesyeBasketDataGridview
is my basket.

Thanks

private void FrooshDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{

if (FrooshDataGridView.RowCount > 0)
{
if (e.RowIndex != -1 && e.ColumnIndex != -1 &&
FrooshDataGridView.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
if (FrooshDataGridView.CurrentCell.Value.ToString().Trim() == "Add to Basket")
if (DialogResult.Yes == MessageBox.Show("Are you shur that to add to basket ", "Add", MessageBoxButtons.YesNo))
{
int a = (int)FrooshDataGridView.CurrentRow.Cells["ID"].Value;
//MessageBox.Show(a.ToString());
string sql = "select * From tblKala where ID =" + a.ToString();
da.SelectCommand.CommandText = sql;
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
DataRow MyRow = table1.NewRow();
MyRow = dt.Rows[0];
table1.ImportRow(MyRow);

}
//NesyeBasketDataGridView.DataSource = null;

//NesyeBasketDataGridView.Show();
}
NesyeBasketDataGridView.DataSource = table1;
}

Answer

Note that, your table1 should have the same structure with the local dt. If not, the row you copy from the dt to the table1 will fill the column from left to right. To copy the structure from the table dt, you can use the Clone method like this:

table1 = dt.Clone();

Your code is wrong because that's not the way to copy a row, you can use the ImportRow directly like this:

table1.ImportRow(dt.Rows[0]);