I have what is a very elementary problem I realize, I am trying to return a string value from a selected value of a DropDownList upon selected index change but for some or other reason it is not happening.
protected void drpMinisters_SelectedIndexChanged(object sender, EventArgs e)
{
name = drpMinisters.SelectedValue;
LabMessage.Text = name;
}
When I try to add name to a database I get a NullReferenceException.
protected void butSubmitMinister_Click(object sender, EventArgs e)
{
int index = drpMinisters.SelectedIndex;
if (index == 0)
{
LabMessage.Text = "Please select a minister";
return;
}
try
{
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = @"INSERT INTO MinisterTable(MinisterName)VALUES(" + name + "')";
cmd.ExecuteNonQuery();
LabMessage.Text = "The record was successfully added";
conn.Close();
}
catch (Exception ex)
{
LabMessage.Text = ex.ToString();
}
}
Advice perhaps.
I assume that you get the
NullRefernceExceptionon your connection objectconnon this line:Remember that all objects (also your
namevariable) are disposed at the end of the current page-lifecycle. You can use the control’s ViewState to maintain values across postbacks, f.e. theSelectedValueproperty of yourDropDownList.You should also create the connection where you use it and always dispose it as soon as you’re finished, best by using the
using-statement. Otherwise other threads(requests) would need to create a new physical connection whenever this is still open: