Home > Back-end >  passing data to datagridview using button
passing data to datagridview using button

Time:10-26

i have a quick question i'm trying to make an application but i've faced a problem, i want to assign data to a button then pass that data to datagridview when the button is clicked ex.

enter image description here

private void TeaButton_Click(object sender, EventArgs e)
        {
            sales.OrderDataGridView.Rows.Add(1, "Tea", 5.0);
        }

i expected it to pass the values inside the parentheses to the data grid view, but it returned a null reference error, the reason was "sales." it was returning null value, but i don't know any other way beside this .

CodePudding user response:

You must first define the DataGridView columns. you can use this code:

    public static Boolean isColumnsAdded = false;
    public static DataTable dt;
    private void TeaButton_Click(object sender, EventArgs e)
    {
        try
        {
//It's better define the columns when loading the form-----------
            if (!isColumnsAdded)
            {
                dt = new DataTable();
                dt.Columns.Add("Amount");
                dt.Columns.Add("Type");
                dt.Columns.Add("Price");
                isColumnsAdded = true;
            }
//--------------------------------------------------------------
            dt.Rows.Add(1, "Tea", 5.0);
            dataGridView1.DataSource = dt;
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }
   }

result:

enter image description here

CodePudding user response:

Just to make sure: is your datagridview is in the same form as the the tea button? if so:

OrderDataGridView.Rows.Add("1", "Tea", "5.0")

and its better to have the values u want to add in " " unless you are going to use variables like :

string TeaStr = "Tea";
OrderDataGridView.Rows.Add("1", TeaStr, "5.0");

if you gonna use float variables, don't forget to add 'f':

float TeaPrice = 5.0f;

your friend mohamed from Egypt <3.

  •  Tags:  
  • c#
  • Related