[英]datagrid get selected rows and cells values in wpf c#
我想在wpf上重做舊的Windows窗體應用程序的代碼,並且在引用datagridview時遇到問題。
這是我的舊應用程序的空白外觀:
private void button2_Click(object sender, EventArgs e)
{
if (DGV1.Rows.Count > 0 && DGV1.SelectedRows != null)
{
bool wart = true;
for (int i = 0; i < listBox2.Items.Count; i++)
{
listBox2.SelectedIndex = i;
int w1 = Int32.Parse(listBox2.SelectedItem.ToString());
int w2 = Int32.Parse(DGV1.SelectedRows[0].Cells[0].Value.ToString());
if (w1 == w2)
{
wart = false;
break;
}
}
if (wart)
{
listBox2.Items.Add(DGV1.SelectedRows[0].Cells[0].Value);
}
}
}
這是我的新應用程序的空白外觀:
private void Button1_Click(object sender, RoutedEventArgs e)
{
IList rows = dataGrid1.SelectedItems;
if(dataGrid1.SelectedItem != null)
{
bool wart = true;
for (int i =0; i < listBox1.Items.Count; i++)
{
listBox1.SelectedIndex = i;
object item = dataGrid1.SelectedItem;
int w1 = Int32.Parse(listBox1.SelectedItem.ToString());
int w2 = Int32.Parse(dataGrid1.SelectedCells[0].Column.GetCellContent(item).ToString()); <--- !!
if(w1 == w2)
{
wart = false;
break;
}
}
if(wart)
{
listBox1.Items.Add(dataGrid1.SelectedCells[0]); <-- !!
}
}
}
請幫忙 :-)
可能應該是這樣的:
listBox1.Items.Add(dataGrid1.CurrentRow.Cells[0].Value);
這段代碼來自WinForms,但是我假設wpf的編碼可能沒有什么不同,因為兩者都在c#中。
dataGrid1.SelectedItem
不僅僅是一些object
,它還具有具體的類型和屬性,例如Id
, Tytul
, Kategorie
, Text
您需要對具體的類型和訪問屬性進行強制轉換,而不是嘗試從DataGridCellInfo等低級UI元素獲取值:
var item = (MyConcreteClass)dataGrid1.SelectedItem;
int w2 = item.Id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.