天天看點

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

WinForm中ListBox資料綁定問題

     這兩天遇到ListBox資料綁定并顯示的問題,以前以為可以根ASP.NET中的用法差不多,即

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

ListBox listBox;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

          listBox.DataSource = ds;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

          listBox.DataTextField = " 要顯示的字段名 " ;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

          listBox.DataValueField = " id " ;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

          listBox.DataBind(); 然後利用listBox.SelectedItem即可通路被選中的項的值,當然在WinForm中除了DataSource的屬性還有,其他都沒有了,WinForm就換成如下方式:

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

                listBox.DataSource = ds.Tables[ 0 ];

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

                listBox.DisplayMember = " carsnumber " ;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

                listBox.ValueMember = " id " ; 這樣便可在ListBox正确顯示出來,并且利用listBox.SelectedValue可以得到標明項的對應的id,  但是當我用

listBox.SelectedItem打算得到相應的carsnumber值時,确顯示System.Data.DataRowView,利用listBox.Item[]通路得到的結果是一樣的。最後在網上搜搜看能不能找到答案,又在CSDN上搜了一下以前的文章,最後找到了答案,

如果要循環通路綁定了的Text值和Value 值,可用如下方式:

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

for ( int i = 0 ; i < listBox.Items.Count; i ++ )

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題
WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題
WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

{

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

     DataRowView drv = listBox.Items[i] as DataRowView;

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

     if( drv != null )

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題
WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題
WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

{

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

           MessageBox.Show( "Text:" + drv[listBox.DisplayMember].ToString() );

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

           MessageBox.Show( "Value:" + drv[listBox.ValueMember].ToString() );

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

     }

WinForm中ListBox資料綁定問題WinForm中ListBox資料綁定問題

}