2016-10-19 5 views
0

オブジェクトの情報をSelectedIndexChangedにしたい、リストボックスでバインドしました。ListBoxでバインドしたSelectedIndexChangedイベントで同じオブジェクトを取得する方法

listbox.bind=list of person object 

forexample

は今のListItemの各リスト上の人物オブジェクトがあり、私はのSelectedIndexChangedイベントでこの人物オブジェクトが必要です。

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 

       //here is the compatibility issue 
       //how can i solve this 
       person ss = ListBox1.SelectedItem as Person; 
     } 
+0

あなたは[ListBox1.SelectedIndex] '私はselectedchangeイベントにコードを確認して –

答えて

0

更新: は、あなたがそのないラージオブジェクト場合は、ビューステートのようにどこかにそれを保存する必要がありますので、ListBox1.DataSourceがポストバック間で永続化されていないことを忘れました。あなたのオブジェクトがSerializable

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     List<Person> persons = new List<Person>(); 

     persons.Add(new Person { Id = 1, Name = "Some Name" }); 
     persons.Add(new Person { Id = 2, Name = "Other Name" }); 

     ViewState["Persons"] = persons; 
     ListBox1.DataSource = persons; 
     ListBox1.DataTextField = "Name"; 
     ListBox1.DataValueField = "Id"; 
     ListBox1.DataBind(); 
    } 
} 

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    List<Person> persons = (List<Person>)ViewState["Persons"]; 
    Person person = persons[ListBox1.SelectedIndex]; 
} 
+0

がnull値を持つdatasouce使用'リストを使用することができなければならないビューステートにそれを保存するには

。 // DataSourceがNULLです リスト人=(リスト)ListBox1.DataSource; – bilal

+0

あなたが正しいです、私は答えを更新しました –

関連する問題