Click here to Skip to main content
15,847,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can anyone suggest the code to fetch the record from database according to the multiple selected value from listbox and display it on gridview in c# window application?
Posted
Updated 15-Nov-12 20:57pm
v2

Hi,

Please write code like below.
C#
string str = "";
foreach(ListItem lstIetm In MyListBox.Items)
{
  If(lstIetm.Selected)
  {
     str+=lstItem.Value.ToString()+",";
  }
}
if(str!="")
{
  str.Remove(str.LastIndexOf(','));
}
//Then write your query with in clause.

Select * from <tableName> where Id in (str)

if you are not able to solve the problem. Please copy here your code snippet.
 
Share this answer
 
v3
Comments
Member 8172875 16-Nov-12 2:01am    
actually i have no idea about this scenario. i have to select multiple ids from listbox and fetch the data of selected ids from database. display records in gridview.
Mohd. Mukhtar 16-Nov-12 2:15am    
please see the above updated answer
Member 8172875 16-Nov-12 2:20am    
thanks for the solution.. i will use it and revert you back...thank you so much
Member 8172875 16-Nov-12 2:55am    
I got an error "unable to cast object of type 'System.String' to 'System.Web.UI.WebControls.ListItem'"
Member 8172875 16-Nov-12 3:17am    
string str = "";
foreach(ListItem lstIetm In MyListBox.Items)// through an exception here "unable to cast object of type 'System.String' to 'System.Web.UI.WebControls.ListItem'"
{
If(lstIetm.Selected)
{
str+=lstItem.Value.ToString()+",";
}
}
if(str!="")
{
str.Remove(str.LastIndexOf(','));
}
//Then write your query with in clause.

Select * from <tableName> where Id in (str)
C#
string str = "";
foreach(ListItem lstIetm In MyListBox.Items)// through an exception here "unable to cast object of type 'System.String' to 'System.Web.UI.WebControls.ListItem'"
{
  If(lstIetm.Selected)
  {
     str+=lstItem.Value.ToString()+",";
  }
}
if(str!="")
{
  str.Remove(str.LastIndexOf(','));
}
//Then write your query with in clause.

Select * from <tableName> where Id in (str)

 
Share this answer
 
Comments
Mohd. Mukhtar 16-Nov-12 3:46am    
MyListBox is your listbox name please verify once again. May be you are getting this error because of incorrect name.
Member 8172875 17-Nov-12 0:39am    
if i write the incorrect name. so i will get a compilation error not run time exception. i used correct name. my sample code is
"
string str = "";


foreach(ListItem lstItem in listBox1.Items)
{
if (lstItem.Selected)
{
//str += listBox1.Items.OfType<string>().ToString();
str+=lstItem.Value.ToString()+",";
}
}
if(str!="")
{
str.Remove(str.LastIndexOf(','));
}
"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900