我想删除数据网格中以及数据库中的多行,但是我什至在删除数据网格中的多行时也遇到问题... 我可以用我的代码删除一行(仅从datagrid中删除),但这还不够。
我正在尝试使用它:
var grid = StudentsDataGrid;
var mygrid = StudentsDataGrid;
if (grid.SelectedIndex >= 0)
{
for (int i = grid.SelectedItems.Count -1; i >= 0; i--)
{
mygrid.Items.Remove(grid.SelectedItems[i]);
};
}
grid = mygrid;
但是我收到一条错误消息,指出使用ItemsSource时操作不正确。而是使用对元素的访问权限,并通过ItemsControl.ItemsSource对其进行更改。
我的方法仅适用于一行:
private void RemoveButton_Click(object sender, EventArgs e){
Student student = StudentsDataGrid.SelectedItem as Student;
StudentsList.Remove(student);
}
也许我应该更改将数据库链接到datagrid的方式。 这是我读取数据库的部分
OpenConection();
using (SqlDataReader dr = DataReader("SELECT IdStudent, FirstName, LastName, Address, IndexNumber, Name FROM apbd.Student INNER JOIN apbd.Studies ON Student.IdStudies = Studies.IdStudies"))
{
list = new ObservableCollection<Student>();
while (dr.Read())
{
string idstudent = dr["IdStudent"].ToString();
string firstname = dr["FirstName"].ToString();
string lastname = dr["LastName"].ToString();
string address = dr["Address"].ToString();
string index = dr["IndexNumber"].ToString();
string studies = dr["Name"].ToString();
if (dr["IdStudent"] != DBNull.Value)
{
int? emp = (int?)dr["IdStudent"];
}
list.Add(new Student
{
IdStudent = idstudent,
Imie = firstname,
Nazwisko = lastname,
Adres = address,
Index = index,
Studia = studies,
});
}
}
CloseConnection();
return list;
}
在主类中,我通过ItemsSource将其链接到DataGrid:
public void LoadDataToDataGrid()
{
StudentsList = new ObservableCollection<Student>();
var instance = new StudentsDbService();
StudentsList = instance.ShowData();
StudentsDataGrid.ItemsSource = StudentsList;
}
好吧,我想我已经找到一种删除datagrid中多行的方法:
private void RemoveButton_Click(object sender, EventArgs e)
{
ObservableCollection<Student> itemsToRemove = new ObservableCollection<Student>();
foreach (Student item in StudentsDataGrid.SelectedItems)
{
itemsToRemove.Add(item);
}
foreach (Student item in itemsToRemove)
{
((ObservableCollection<Student>)StudentsDataGrid.ItemsSource).Remove(item);
}
}
但是现在如何从数据库中删除特定记录? 我是否应该将以前通过的IdStudent作为学生对象中的值之一传递?
猜猜我找到了一种方法,但是请告诉我它有多糟?
这是修改后的部分,负责从DataGrid中删除记录:
private void RemoveButton_Click(object sender, EventArgs e)
{
ObservableCollection<Student> itemsToRemove = new ObservableCollection<Student>();
List<string> studentID = new List<string>();
foreach (Student item in StudentsDataGrid.SelectedItems)
{
itemsToRemove.Add(item);
studentID.Add(item.IdStudent);
}
foreach (Student item in itemsToRemove)
{
((ObservableCollection<Student>)StudentsDataGrid.ItemsSource).Remove(item);
}
var instance = new StudentsDbService();
instance.deleteRecords(studentID);
}
这是我从数据库中删除记录的部分:
public void deleteRecords(List<string> studentID)
{
OpenConection();
foreach (string item in studentID)
{
ExecuteQueries("DELETE FROM apbd.Student WHERE IdStudent=" + item);
}
CloseConnection();
}