尝试在WPF中绑定DataTable时,DataGrid中未显示“第一列”值.
码
private DataTable _dt;
public DataTable DataTable
{
get { return _dt; }
set { _dt = value; }
}
public Controls()
{
InitializeComponent();
_dt = new DataTable("Table");
_dt.Columns.Add("S.No");
_dt.Columns.Add("Name");
for (int i = 1; i <= 10; i++)
{
_dt.Rows.Add(""+i, "Name "+ i);
}
dataGrid1.DataContext = _dt;
}
XAML
<DataGrid AutoGenerateColumns="True"
Height="131"
ItemsSource="{Binding}"
HorizontalAlignment="Left"
Name="dataGrid1"
VerticalAlignment="Top"
Width="359" />
解决方法:
列的名称不能包含点或空格字符,DataBinding不支持在列名称中使用点.这不仅在DataGrid AutoGenerateColumns中而且在绑定系统中的所有地方都无法正常使用.
尝试将S.No更改为仅读取No,如以下代码所示:
_dt = new DataTable("Table");
_dt.Columns.Add("No");
_dt.Columns.Add("Name");
DataRow dr = _dt.NewRow();
for (int i = 1; i <= 10; i++)
{
_dt.Rows.Add(""+i, "Name "+ i);
}
dataGrid1.DataContext = _dt;