views:

40

answers:

2

Hey,

I just started writing a customer application in C#, using Visual Studio design mode for most of it. Bear in mind I only started learning C# yesterday - so if I am making any stupid mistakes then please say so.

What I have so far

  • A database;
  • A DataSet which links to the Customer and Agent tables;
  • A BindingSource which binds to the DataSet;
  • A CustomerBindingSource which binds to the Customer table of the BindingSource;
  • An AgentBindingSource which binds to the Agent table of the BindingSource;
  • A DataGridView which binds to the CustomerBindingSource, of which the AgentID column is a combobox which binds to the AgentBindingSource.

So far this is working ok. However I have a couple of problems, one of which is in the following code...

The Code

void grdCustomers_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    DataGridViewRow gvr = grdCustomers.Rows[e.RowIndex];
    String currID = gvr.Cells[0].Value.ToString();
    if (currID.Equals(""))
    {
        gvr.Cells[0].Value = "{id}";
    }
}
void button1_Click(object sender, EventArgs e) //Save button for when the user has finished editing.
{
    foreach (DataGridViewRow gvr in grdCustomers.Rows)
    {
        String currID = gvr.Cells[0].Value.ToString();
        if (currID.Equals("{id}"))
        {
            String g = Guid.NewGuid().ToString();
            gvr.Cells[0].Value = g;
        }
    }
    customerTableAdapter.Update(customerAppDS21.Customer);
}

The Problems

  1. The 4th line is causing issues when trying to run the program. It is saying that the object reference is not set to an instance of an object. I think this is caused by the gvr.Cells[0], but I dont know why. In my mind it would make sense if this was called when the setup of a row is complete (including adding all the cells).

  2. I cannot get the DataGridView to bind the data to the database. I want the user to be able to edit any of the values, but when they add a row the id is not calculated until they click the Save button (button1).

I would greatly appreciate it if someone could help me out with either of these problems.

Regards,

Richard

+1  A: 

Hi, it is the ”Value” which is null. The default value of a cell is always null. This means that you might read it before it has been populated or that column just don’t have any value. Check to see if it is null before you try to access it. If it is null that cell has no value.

Mikael
See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.value.aspx
Mikael
A: 

Its my experience that modifying contents of a cell is easier in the cellFormatted event handler.

DevelopingChris