Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I am developing window application in c# .net, problem is
i have added datagridviewtextboxcolumn to datagridview, when Student Batch is selected coresponding students are populated in datagridview now i have three columns in dg 1:Student (all students names) 2:Present/Absent (checbox column) 3:Reason
Number 3 column is datagridviewtextboxcolumn, now when i save record from datagridview to database then there are two scenarios a: if 'reason column' cell contain some text then record is saved b:if there is no text in 3rd column cell then error is generated "Object reference not set to an instance of an object." i.e if there is no text cell of datagridviewtextboxcolumn then its object is not created
Please i want quick response.
Posted

1 solution

There are different ways to solve this issue.

1. You have a DataSet that you use as the data source for the data grid
In this case you can change the behavior of the column to return an empty string instead of DbNull

2. Change the code used to save the data
You are not showing your code but this an example of how to do it

Assuming Reason is the name of your column.
C#
string s = (dg["Reason", i] == null) ? "" : dg["Reason", i].Value.ToString());
da.Parameters("@Reason", s);
 
Share this answer
 
v7
Comments
Abdullah Kundi 30-Jun-14 4:14am    
this is my code
private void insert()
{
for (int i = 0; i < dg.Rows.Count; i++)
{
string celValue = dg.Rows[i].Cells["Student"].Value.ToString();
int stdNo = da.fetchKeyStudent(celValue);
da.ProcName = "AddStudentsAttendance";
da.OpenDBConnection();
da.CreateCommandObject();
da.Parameters("@Date", txtDate.Text);
da.Parameters("@keyEmployee", int.Parse(txtEmployee.SelectedValue.ToString()));
da.Parameters("@KeyStudent", stdNo);
da.Parameters("@Present", Convert.ToBoolean(dg.Rows[i].Cells["Present"].Value));

da.Parameters("@Reason", dg.Rows[i].Cells["Reason"].Value.ToString());
da.Parameters("@UpdOperation", 0);
da.ExecuteNonQuery();
da.CloseConnection();

}

dg.DataSource = null;

Empty();
}
George Jonsson 30-Jun-14 4:18am    
I updated my answer to reflect your code.
Abdullah Kundi 30-Jun-14 4:58am    
string s = (dg["Reason", i].Value == null)in this line of code same error
R/Sir if cell is empty then it gives same problem 'object reference not set to an instance of object'
George Jonsson 30-Jun-14 6:25am    
Sorry. It should be
string s = (dg["Reason", i] == null)
My copy and paste error.
I have updated my solution.
Abdullah Kundi 30-Jun-14 6:03am    
Good shot , Sir it solved my problem

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900