2012-08-09 67 views
0
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; 
} 

如何添加新行,點擊我的按鈕?謝謝:)如何在datagrid中添加新行(源數據表)

回答

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

嘗試此代碼

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; 

} 
相關問題