C# 添加datatable行和列并更新datagridview
如何添加结果,而不仅仅是替换上一个结果。这是所要求的全部代码。我只是不知道它是否需要手动添加行,或者有一个简单的方法来实现它。提前感谢首先,您应该使用 然后,您只需要将代码放入某种类型的事件处理程序中。我想用户可能会按enter键或C# 添加datatable行和列并更新datagridview,c#,database,C#,Database,如何添加结果,而不仅仅是替换上一个结果。这是所要求的全部代码。我只是不知道它是否需要手动添加行,或者有一个简单的方法来实现它。提前感谢首先,您应该使用 然后,您只需要将代码放入某种类型的事件处理程序中。我想用户可能会按enter键或文本框中的某个键 只要不清除数据表,它就会在每次运行查询时不断添加行。如果您想在代码中的其他点清除该表,只需调用dt.clear() 像这样的东西应该能得到你想要的,并且不会被注射: string conString = "Server=192
文本框中的某个键
只要不清除数据表
,它就会在每次运行查询时不断添加行。如果您想在代码中的其他点清除该表,只需调用dt.clear()
像这样的东西应该能得到你想要的,并且不会被注射:
string conString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
MySqlConnection conn = new MySqlConnection(conString);
DataTable dt = new DataTable();
DataRow row = dt.NewRow();
conn.Open();
//cmd = conn.CreateCommand();
//cmd.CommandText = "Select * From tblindividualproduct";
if (e.KeyCode == Keys.Enter)
{
if (txtBarcode.Text == "")
{
MessageBox.Show("Please Fill the correct ProductID");
}
else
{
string sql = "Select * From tblindividualproduct where ProductID = @ProductIdText";
using (var adapt = new MySqlDataAdapter(sql, conn))
using (var cmd = new MySqlCommandBuilder(adapt)) //Not sure what you need this for unless you are going to update the database later.
{
adapt.SelectCommand.Parameters.AddWithValue("@ProductIdText", txtBarcode.Text);
BindingSource bs = new BindingSource();
adapt.Fill(dt);
bs.DataSource = dt;
dgItems.ReadOnly = true;
dgItems.DataSource = bs;
}
}
}
然后确保您已将此事件附加到文本框中窗体中的某个位置,如下所示:
private void txtBarCode_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if(String.IsNullOrEmpty(txtBarcode.Text))
{
MessageBox.Show("Please Fill the correct ProductID");
}
else
{
string sql = "Select * From tblindividualproduct where ProductID = @ProductIdText";
using (var adapt = new MySqlDataAdapter(sql, conn))
using (var cmd = new MySqlCommandBuilder(adapt)) //Not sure what you need this for unless you are going to update the database later.
{
adapt.SelectCommand.Parameters.AddWithValue("@ProductIdText", txtBarCode.Text);
BindingSource bs = new BindingSource();
adapt.Fill(dt);
bs.DataSource = dt;
dgItems.ReadOnly = true;
dgItems.DataSource = bs;
}
}
}
}
现在,当用户在框中键入并按enter键时,查询将运行,结果将显示在DataGridView
中。无需手动添加列和行,adapt.Fill(dt)
将为您执行此操作。您没有使用绑定源代码,您分配了它,但从未绑定到它。它应该是dgtems.DataSource=bs
除此之外,您的意思是想在dt
中添加行/列吗?当我在文本框中输入2时,它将显示产品id为2的产品,当我想输入3时,我希望它添加新行,并在gridview中显示产品2和3。谢谢您,但gridview仍在更新,没有添加任何行。每次我按enter键时,它只显示1个结果。需要查看创建数据表的代码
您可能正在反复创建数据表
,以清除它。你应该在类级别声明它。你知道了吗?只需在类级别声明DataTable
,并在表单的整个生命周期中使用它。尽管我建议您考虑将数据访问层与表示层分离,但我将DataTable放在了部分类Form1中,这是可行的!只需确保在处理完它时调用Dispose()
,因为它是非托管的。
this.txtBarCode.KeyUP += txtBarCode_KeyUp;