简体   繁体   中英

c# getting NullReferenceException when retrieving data from a cell in DataGridView

This is my code:

private void CostList_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'lSEStockDataSet.CostPrice' table. You can move, or remove it, as needed.
    this.costPriceTableAdapter.Fill(this.lSEStockDataSet.CostPrice);

    con = new System.Data.SqlClient.SqlConnection();
    con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
    con.Open();

    DataGridView datagridview1 = new DataGridView();
    String retrieveData = "SELECT CostID, SupplierName, CostPrice FROM CostPrice WHERE PartsID ='" + textBox1.Text + "'";
    SqlCommand cmd = new SqlCommand(retrieveData, con);
    int count = cmd.ExecuteNonQuery();
    SqlDataReader dr = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(dr);
    dataGridView1.DataSource = dt;
    con.Close();

}

private void button1_Click(object sender, EventArgs e)
{

    if (dataGridView1.Rows.Count > 0)
    {   
        int nRowIndex = dataGridView1.Rows.Count-1;


        if (dataGridView1.Rows[nRowIndex].Cells[2].Value != null)
        {
            textBox2.Text = Convert.ToString(dataGridView1.Rows[nRowIndex].Cells[2].Value);
        }
        else
        {
            MessageBox.Show("NULL");
        }
    }
}

It shows NULL when i clikc the button, what is the problem here? I have 3 columns there, i want to get the data of the 3rd column of the last row, but it shows NULL but there is data in the specified cell. Anyone knows how to solve this problem?

Instead of subtracting one from the row count, try subtracting two. Subtracting one is giving you the zero-based index of the "add" row, which indeed has a null value in the last column.

    int nRowIndex = dataGridView1.Rows.Count-2;

By subtracting 2 from the count, you will get the zero-based index of the last row with actual data in it. I think this is what you are looking for.

As an aside, you will likely want to parameterize your SQL query, something like this:

String retrieveData = "SELECT CostID, SupplierName, CostPrice FROM CostPrice WHERE PartsID = @inPartsID";
SqlCommand cmd = new SqlCommand(retrieveData, con);
cmd.Parameters.Add(new SqlParameter("@inPartsID", textBox1.Text));

This will make your query more reliable (what happens if there is a single quote character in textBox1) and your data more secure (evil-doers can use SQL injection to cause harm to your database or get data out of it that they shouldn't).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM