开发者

How to Retrieve data from selected ListBox?

In C#.Net ,I'm trying to retrieve data from selected ListBox.

Eg. First I displayed many data in ListBox that retrieved from MSSQL 2008 Database. When i select single data from that listbox , i want to show that selected data into textb开发者_JS百科ox... How can i do that? I need yours answers because i'm just beginner , Please answer me if you know.. Thanks


It really depends on how you stored your data into the list. Is that simple string or some complex object, is either case you can cast the selected item to it's appropriate type. For example. If your list box contains only string type items, you will get the selected item by

string value=(string) this.listBox1.SelectedItem;

If your listbox contains other Complex type, you will get the selected item by

SomeComplexObject value=(SomeComplexObject) this.listBox1.SelectedItem;

Or if you have binded listbox to some sort of datatable or dataset. you can get the value of the selected item using

string value=listBox1.SelectedValue.ToString();

So now, When listbox selected index changed. you can set textbox value using. First, subscribe to listbox index changed event

 this.listBox1.SelectedIndexChanged+=new EventHandler(changed);

And your handler.

 private void changed(object sender,EventArgs args)
        {
            //set your text box text property here
            //with the code provided earlier
        }


Trap the ListBox SelectedIndexChanged event, for example you can do,

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    textBox1.Text = listBox1.SelectedItem.ToString(); //let textBox1 be your TextBox name and listBox1 be your ListBox name
}


In ASP.NET use below code:

var selectedValue = listBoxObj.SelectedItem.value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜