Reputation: 127
Basically I want to add another column from a TextBox
along with values I have queried from the database. I want my datagridview to show something like
|itemcode|Category|itemDescription|unitcost|quantity|
where itemcode, Category, itemDescription, unitcost
is from database and quantity
is from a text box input.
private void btnAddToCart_Click(object sender, EventArgs e)
{
con.OpenConnection();
MySqlCommand cmd = con.connection.CreateCommand();
string search = txtSearchProduct.Text;
string quantity = txtQuantity.Text;
string query = "SELECT itemcode, Category, itemDescription, unitcost FROM tblprowareproducts WHERE itemDescription LIKE ?search";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?search", "%" + search + "%");
using (MySqlDataAdapter mda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
mda.Fill(dt);
dgvCart.DataSource = dt;
}
}
Is there a way to add another column after unitcost
named quantity
and the value of it comes from a TextBox
?
Upvotes: 1
Views: 276
Reputation: 125207
There are different solutions for the problem, for example you can add the column to DataTable
this way:
DataTable dt = new DataTable();
mda.Fill(dt);
var quantity = dt.Columns.Add("quantity", typeof(int));
quantity.DefaultValue = int.Parse(txtQuantity.Text);
dt.AsEnumerable().ToList().ForEach(r =>
{
r[quantity] = quantity.DefaultValue;
});
dgvCart.DataSource = dt;
Note 1: You may want to use TryParse
to get the integer value from text.
Note 2: Default value of column applies to the column when adding the row. So to apply it to existing rows, you need to use a loop like what I did. For new rows that you add after that, it will be applied automatically.
Upvotes: 1