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
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
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).
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
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.
It seems that you add a new row with null values then you assign data to it. Try to change the way you add row to grid
我的经验是,在cellFormatted事件处理程序中修改单元格的内容会更容易。
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.