如何在wpf中获取datagrid特定的单元格值? [英] how to get datagrid particular cell value in wpf ?
问题描述
嗨朋友们,
在我的项目中,我放了一个 DataGrid
来查看数据库数据。现在我想要在DataGrid中选择的单元格值。
我的代码
Hi Friends,
In my project I put one DataGrid
for viewing database data. Now I want the cell value which I selected in the DataGrid.
for that I code
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
textBox1.Text = dataGrid1.SelectedItem.ToString();// TextSelection;
}
我只想要代码名称。 :-\即'cs11'。但我得到了
I want the code name only. :-\ that is 'cs11'. but I got
{ name = tuutusdydfh, code = cs11 }
。,
所以我也试试这些代码。
.,
so I try these code also.
// textBox1.Text = dataGrid1.SelectedCells[1].ToString();
//textBox1.Text = dataGrid1.CurrentCell.Item.ToString();
// textBox1.Text = dataGrid1.ItemsSource.ToString();
//textBox1.Text = dataGrid1.Items.ToString();
但是我不能得到。我只想要代码名称,帮帮我朋友。
我的数据网格(xaml): -
but I cant get. I want the code name only, help me friends.
My Data Grid (xaml):-
<datagrid name="dataGrid1" itemssource="{Binding }" borderbrush="Gray" borderthickness="5" margin="45,91,30,116">
Background="LightGray"
RowBackground="SeaShell"
RowHeight="30"
ColumnWidth="150"
AlternatingRowremoved="Lavender"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
MouseDoubleClick="dataGrid1_MouseDoubleClick"
SelectionChanged="dataGrid1_SelectionChanged" /></datagrid>
代码: -
Code :-
if (paramType == "Hall")
{
//var dbList = from recs in MainWindow.mcsEntity.mcs_hall orderby recs.mcs_Hall_Name
// select recs;
//dataGrid1.DataContext = dbList;
dataGrid1.DataContext = from re in MainWindow.mcsEntity.mcs_hall
orderby re.mcs_Hall_Code
select new
{
name = re.mcs_Hall_Name,
code = re.mcs_Hall_Code
};
}
推荐答案
你可以使用一个班级
Hi,
you can use a class
public class MyClass
{
public string Name {get;set;}
public int Code { get; set; }
}
并在Linqstatement中创建no var。您可以在班级中创建新对象:
and create in the Linqstatement no var. You create new objects from your class:
dataGrid1.DataContext = from re in MainWindow.mcsEntity.mcs_hall
orderby re.mcs_Hall_Code
select new MyClass
{
Name = re.mcs_Hall_Name,
Code = re.mcs_Hall_Code
};
你的SelectionChanged事件中的
你将selectedItem转换为你的类:
in your SelectionChanged event you convert the selectedItem to your class:
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
textBox1.Text = (e.AddedItems[0] as MyClass).Name;
}
}
希望有帮助
Hope that helps
我认为此 [ ^ MSDN上的线程有您正在寻找的解决方案。
I think that this[^] thread on MSDN has the solution you are looking for.
for (int j = 0; j < dataGrid1.Columns.Count; j++)
{
for (int i = 0; i < dataGrid1.Items.Count - 1; i++)
{
string s=(dataGrid1.Items[i] as DataRowView).Row.ItemArray[j].ToString();
}
}
这篇关于如何在wpf中获取datagrid特定的单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!