[英]datagrid get selected rows and cells values in wpf c#
I would like to redo the code of my old windows forms application on wpf and I have a problem with referencing datagridview. 我想在wpf上重做旧的Windows窗体应用程序的代码,并且在引用datagridview时遇到问题。
This is the void look of my old application: 这是我的旧应用程序的空白外观:
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);
}
}
}
This is the void look of my new application: 这是我的新应用程序的空白外观:
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]); <-- !!
}
}
}
The application spills out at the second if, where it displays: 如果该应用程序显示在以下位置,则会在第二个位置溢出:
Please Help :-) 请帮忙 :-)
It should probably be like this: 可能应该是这样的:
listBox1.Items.Add(dataGrid1.CurrentRow.Cells[0].Value);
This code is from WinForms, but I assume the coding for wpf may not be different, since both are in c#. 这段代码来自WinForms,但是我假设wpf的编码可能没有什么不同,因为两者都在c#中。
dataGrid1.SelectedItem
isn't just some object
, it has concrete type and properties like Id
, Tytul
, Kategorie
, Text
dataGrid1.SelectedItem
不仅仅是一些object
,它还具有具体的类型和属性,例如Id
, Tytul
, Kategorie
, Text
you need to make a cast to that concrete type and access property instead of trying to get the value from low-level UI elements like DataGridCellInfo: 您需要对具体的类型和访问属性进行强制转换,而不是尝试从DataGridCellInfo等低级UI元素获取值:
var item = (MyConcreteClass)dataGrid1.SelectedItem;
int w2 = item.Id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.