Hello Friends,
I m Developing an windows form application. i have a winform on which i have datagridview and i am saving the data to Sql Server database
from datagridview directly . i m using the following code for connecting & saving data of datagridview to database using button click . though i am suscessful
in connecting to database and also saving data to database after my data is saved i get following error
"Object reference Not set to Instance of object" and after clicking on ok i get second error message
"Must declare the scalar variable @Jour" which i have already declared
following are the names of controls and database object
"dgJrn"l is Datagridview
"JournalEntry " is Table in Database named "TMSDB"
"JournalType "is Column in "JournalEntry" Table
"JournalHead" is Column in Datagridview
and "@jour" is parameter
Waiting for your help
private void btnRecord_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(@"Data Source=(local)\SQLEXPRESS;Integrated Security=true;Initial Catalog=TMSDB");
foreach (DataGridViewRow dr in dgJrnl.Rows)
{
SqlCommand cmd = new SqlCommand("Insert into JournalEntry (JournalType) values(@Jour)", cn);
cmd.Parameters.AddWithValue("@Jour", dr.Cells["JournalHead"].Value.ToString ());
cn.Open();
try
{
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("Data Stored");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}