HI, I'm really struggling - if anyone can help I would really apprecaite it.
I have a listbox populated by a SQL database.
I have set the binding of the listbox in a if(!this.ispostback) block
I have a button that eventually will run a query and update the datebase, based on what is selected in the listbox.
Every time that button is clicked, the selection is lost and therefore there is a Null Exemption when trying to get the value of the selected item in the listbox.
here is the code - please can you help
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
bind();
}
}
private void bind()
{
DataSet ds = new DataSet();
string constring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string queryShrewsbury = "Select Callsign, Info FROM Trucks WHERE Location Like'Shrewsbury'";
//string queryDonnington = "Select Callsign, Info FROM Trucks WHERE Location Like'Donnington'";
SqlConnection conn1 = new SqlConnection(constring);
conn1.Open();
SqlDataAdapter adp = new SqlDataAdapter(queryShrewsbury, constring);
adp.Fill(ds);
Shrewsbury_listbox.DataSource = ds;
Shrewsbury_listbox.DataTextField = "Callsign";
Shrewsbury_listbox.DataValueField = "Info";
Shrewsbury_listbox.DataBind();
conn1.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Shrewsbury_listbox.SelectedIndex == -1)
{
Response.Write("it didn't work");
}
else
{
string value = Shrewsbury_listbox.SelectedItem.Value;
Response.Write(value + "it worked");
}
}
HTML
<body>
<form>
<asp:ListBox ID="Shrewsbury_listbox" runat="server" Height="153px" Width="225px">
</asp:ListBox>
<br />
<asp:Button ID="Button1" runat="server" Text=">>" OnClick="Button1_Click" Height="53px"
Width="221px" />
</form>
</body>