listbox control - valuemember & selectedvalue

  • Thread starter Thread starter Pat
  • Start date Start date
P

Pat

I'm a newbie to c# and could use some help - been banging my head on
the keyboard for 3 days now.

I have an unbound listbox that I'm populating this way:

1. loop through a datatable and load row into row object
2. Check one of the row columns against a dictionary key
3. If it's found, add it to the listbox.

Then I want to pass the actual item that shows up in the listbox
(empname) and the valuemember (empnum) to another form via properties
(I think). But I cannot get the value unless I bind the listbox to the
datatable - and then I get all the rows in the table, even if I set the
source "above" the loop. What I get is an error on the line where I
try to extract the selectedvalue.

public void LoadListBox()
{
dtEmp = taEmp.GetData();

for (int i = 0; i < dtEmp.Count; i++)
{
rEmp = dtEmp;
lbAssignedEmps.DisplayMember = rEmp.EMPNAME;
lbAssignedEmps.ValueMember = rEmp.EMPNUM;
// lbAssignedEmps.SelectedValue = rEmp.EMPNUM;

if (htPass.ContainsKey(rEmp.EMPNUM))
{
this.lbAssignedEmps.Items.Add(rEmp.EMPNAME);
}
}
}

then:

private void btnEdit_Click(object sender, EventArgs e)
{

string sEmpName = "";
string sEmpNumber = "";
string sPassword = "";

int iIndex = 0;
iIndex = lbAssignedEmps.SelectedIndex;


sEmpName = lbAssignedEmps.SelectedItem.ToString();
sEmpNumber = lbAssignedEmps.SelectedValue.ToString(); ERROR
HERE!!
more stuff...
}

It says I must use the new keyword to create an instance of something -
I tried DataView, all sorts of things for 3 days.

I think a dictionary with a dictionary key (or value) would work, like
Dictionary<Dictionary<string, string>, string>. I can declare it but
can't figure out how to populate it or extract it (syntax for the inner
dictionary). I need to write it to a .csv and then read it back into a
dictionary and again, use it to populate list boxes.

any help would be greatly appreciated!!! TIA
Pat
 
Why don't you just create a new DataTable, fill it with new rows containing
only the ItemArray information that passes your "test", and then bind with
that?

Also, it's getting a bit late here, but I'm wondering if your first line
here:

sEmpName = lbAssignedEmps.SelectedItem.ToString(); <<-----
sEmpNumber = lbAssignedEmps.SelectedValue.ToString(); ERROR

-shouldn't it be "SelectedItem.Text" instead of SelectedItem? SelectedItem
is a ListItem, not sure if that would work.


Cheers,
Peter
 
Thanks, Peter

After much fiddling, I finally got the whole dataset, datatable,
datarow thing working. It was much easier when loading a datatable
from the DB!! My main experience is backend database programming, and
though I've done some vb6 work on an existing product, starting from
scratch on c# front-end is fun, but challenging!

Thanks again,
Pat
 
Back
Top