Arbnor Salihu

Arbnor Salihu

  • NA
  • 15
  • 759

C# get the value of certain item in listbox

Nov 9 2016 4:29 PM

I'm trying to get the value of certain item from listBox, because in my listBox1 I have two different values that have comes from dataGridView. Now, I need to separate these two items separately because it must add to the database in two different columns.

Now, how to to get only value of Name, and only value of Surname.

I tried like the following code, but I get an error(invalidargument=value of '1' is not valid for 'index'. parameter name: index)

 
 
 
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in dataGridView1.SelectedCells)
{
cell = selectedCell;
break;
}
if (listBox1.Items == null)
{
MessageBox.Show("Please, select an Employee!");
}
else
{
string str = "";
for (int i = 0; i <= listBox1.Items.Count-1; i++)
{
if (listBox1.Items[i] != null)
{
if (str == "")
{
str = listBox1.Items[i].ToString();
}
else
{
str += "," + listBox1.Items[i].ToString();
}
}
}
cmd.Parameters.AddWithValue("@empName", listBox1.Items[0].ToString());
cmd.Parameters.AddWithValue("@empSurname", listBox1.Items[1].ToString());

Attachment: Capture.rar

Answers (2)

0
Bikesh Srivastava

Bikesh Srivastava

  • 81
  • 23.9k
  • 3.5m
Nov 10 2016 11:59 PM
Hi,
I think you are doing good ,but you have change some little bit of code,
 
And do one thing for next time,Please try to post code in block ,because its difficult  to understand  for Experts.
0
Madhanmohan Devarajan

Madhanmohan Devarajan

  • 231
  • 8.2k
  • 1.7m
Nov 10 2016 2:21 PM
Arbnor,
 
In your case you have one listbox having items in the format of "EmpFirstname, EmpSurname". In order to extract Firstname and Surname you may need to use split method as shown the below in highlighted section.
 
DataGridViewCell cell = null;
foreach (DataGridViewCell selectedCell in dataGridView1.SelectedCells)
{
   cell = selectedCell; break;
 }
  if (listBox1.Items == null)
   {
     MessageBox.Show("Please, select an Employee!");
   }
  else
  {
   string str = "";
   str = (listBox1.SelectedItem as ListData).Text;     
 string[] strEmpName = str.Split(',');
  cmd.Parameters.AddWithValue("@empName", strEmpName[0].ToString()); 
    cmd.Parameters.AddWithValue("@empSurname", strEmpName[1].ToString()); 
  }
}
 
Create a class for ListData
public class ListData {     
 public string Value { get; set; };     
 public string Text { get; set; }; 
}