1

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?

2
  • And what's the problem? What's the expected result? What's the result which you received? Commented Sep 22, 2017 at 3:57
  • updated my question Commented Sep 22, 2017 at 4:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.