DataTable嵌入DataGrid,DataTable可以通过Rows和Columns删除行和列
private void AddData_Click(object sender, RoutedEventArgs e)
{
DataRow dr = dt.NewRow();
for (int columIndex = 0; columIndex < dt.Columns.Count; columIndex++)
{
if (columIndex == 0)
dr[columIndex] = "第" + dt.Rows.Count.ToString() + "组";
else
dr[columIndex] = "";
//dr[columIndex] = dt.Rows.Count.ToString() + " - " + columIndex.ToString();
}
dt.Rows.Add(dr);
}
int newColumnIndex = 5;
//增加一列
private void AddColumn_Click(object sender, RoutedEventArgs e)
{
dt.Columns.Add(new DataColumn("" + newColumnIndex++));
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == 0)
dt.Rows[i][dt.Columns.Count - 1] = "A" + (newColumnIndex - 1).ToString();
else
dt.Rows[i][dt.Columns.Count - 1] = "";
//dt.Rows[i][dt.Columns.Count - 1] = i.ToString() + " - " + (newColumnIndex - 1).ToString();
}
dataGrid.ItemsSource = null;
dataGrid.ItemsSource = dt.DefaultView;
}
//删除一行
private void DeleteData_Click(object sender, RoutedEventArgs e)
{
if (dt.Rows.Count > 2)
{
if (dataGrid.SelectedIndex != -1 && dataGrid.SelectedIndex != 0 && dataGrid.SelectedIndex != dt.Rows.Count)
{
dt.Rows.RemoveAt(dataGrid.SelectedIndex);
}
else
{
dt.Rows.RemoveAt(dt.Rows.Count - 1);
}
}
}
用数据绑定,直接删除数据就可以了,不需要操作datagrid
可以讲述据读出到临时的表中,然后绑定到datagrid里,之后在临时的表中将想要删除的那一行删除