private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add("1","John");
dataGrid1.ItemsSource = dt.DefaultView;
}
如何添加新行,点击我的按钮?谢谢:))
答案 0 :(得分:3)
示例代码:
动态创建表,添加cloumn,添加行
1-创建新的DataTable
DataTable dt = new DataTable ("Table_AX");
2-将列添加到DataTable
// Method 1
dt.Columns.Add ("column0", System.Type.GetType ("System.String"));
// Method 2
DataColumn dc = new DataColumn("column1",System.Type.GetType("System.Boolean"));
dt.Columns.Add (dc);
3-向DataTable添加行
// Initialize the row
DataRow dr = dt.NewRow ();
dr ["column0"] = "AX";
dr ["column1"] = true;
dt.Rows.Add (dr);
// Doesn't initialize the row
DataRow dr1 = dt.NewRow ();
dt.Rows.Add (dr1);
private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id",System.Type.GetType ("System.String"));
dt.Columns.Add("Name",System.Type.GetType ("System.String"));
DataRow dr=dt.NewROw();
dr[0]="a";
dr[1]="abc";
dt.Rows.Add(dr);
dataGrid1.ItemsSource = dt.DefaultView;
}
答案 1 :(得分:1)
试试此代码
private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["id"]="testid";
dr["Name"] = "testname";
dt.Rows.Add(dr);
dataGrid1.ItemsSource = dt.DefaultView;
}