Hi
I have the following code in an asp.net file:
<div id="header">
Home     |   Computers     |   Laptops     |   PDAs     |   Accessories     |   Networks     |   Monitors     |   Keyboards/Mice    
</div>
<asp:ListBox ID="lbsmenu" runat="server" SelectionMode=Multiple></asp:ListBox>
<form id="form1" runat="server">
<p> Enter Name </p>
<asp:TextBox ID="tbBike" runat="server" > </asp:TextBox>
<br />
<asp:Button ID="btBike" runat="server" Text="Click Here" OnClick="btBike_Click" />
<br />
</form>
</div>
I also have the following code in a c# file:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlConn = connection.connect();
sqlConn.Open();
SqlCommand menubar = new SqlCommand("Select * from Menu_table", sqlConn);
SqlDataAdapter dataAdapter5 = new SqlDataAdapter();
dataAdapter5.SelectCommand = menubar;
DataSet dataSet5 = new DataSet();
dataAdapter5.Fill(dataSet5);
DataTable selcartest4 = dataSet5.Tables["table"];
for (int i = 0; i < selcartest4.Rows.Count; i++)
{
Session["selCommunities"] = selcartest4.Rows[i]["Menu_id"].ToString().Trim();
string selCommunities = Session["selCommunities"].ToString().Trim();
lbsmenu.Items.FindByValue(selCommunities).Selected = true;
}
}
However I keep getting an object reference error for the lbsmenu bit of code shown above.
I am using visual web developer
Any solutions would be great
cheers
Jamie
Have you initialized lbsmenu.Items collection with values anywhere? Otherwise the items collection is nothing.
You should populate lbsMenu's ListItem collection with list values.
Make sure you set the
DataValueField
or else if you use
new ListItem(<text>,<value>);
check whether <value> is set.
Since you use FindByValue(string searchkey), which is case sensitive, returns null item if list items value doesn't match with the searchkey.
Sorry I am not sure what you mean, could you give me an example please
thankyou
Sorry for late reply,
Did you set data source for the ListBox or add list item manually?
If former case ,
you should set
DataValueFieldof the list box before calling
FindByValue
method.
If latter case,
which means you populate list box by calling
ListBox1.Items.Add(new ListItem("Text here","Value here"));
second parameter we can omit. But it should set, before calling
FindByValue
Other thing is, parameter value for the FindByValue is case sensitive. if that doesn't match it will returns null listItem. then you will get object reference error.
Hope you got the answer.
Hi James,
I agree with the member above. We should make sure that the item we get using FindByValue method is not null.
Besides, the ListBox control should be placed within a form tag with runat=server.
I hope this helps.
0 comments:
Post a Comment