I am using listbox for the first time in my asp.net C# website. I want the user to be able to select multiple items from the listbox and later on the button click event the selected items will be displayed in the label.
I have searched alot on google.. came across many solutions bt non of them worked for me.
I dnt know why m i getting this weird error out of nowhere.
my aspx code:
<asp:ListBox ID="ListBox1" SelectionMode="Multiple" AutoPostBack="true" DataTextField="area"
DataValueField="area" runat="server" Height="139px" Width="239px"
onselectedindexchanged="ListBox1_SelectedIndexChanged">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
You Choosed<br />
<asp:Label ID="Label1" runat="server">
my code behind aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
bindlist();
if (!IsPostBack)
{
bindlist();
}
}
protected void bindlist()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=SARU-PC\\SQLEXPRESS;Initial Catalog=jd;Integrated Security=True";
SqlDataAdapter adp = new SqlDataAdapter("select area from area", conn);
DataSet ds = new DataSet();
adp.Fill(ds);
ListBox1.DataSource = ds;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
ListItem item = ListBox1.SelectedItem;
string a = item.Text;
Label1.Text = a;
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
string a = ListBox1.SelectedItem.ToString();
Label1.Text += a + "<br />";
}
1) I loaded my listbox from database in page load event later i replaced with existing code just in case.
2) I tried getting selected items on button click in label bt later i even tried getting it on selectedindexchanged event. it still doesnt work.
3) have tried diff ways of assigning selected items of listbox in label bt all in vain.
I am getting the"Object reference not set to an instance of an object" error on the line where i assign "listbox1.selecteditem" to a string or to the label itself.
Please help!!!!