如何在插入新行后对数据集进行排序? [英] How do I sort a dataset after inserting new rows?
问题描述
大家好,
我遇到了这个问题,所以我希望有人可以帮助我。
我有一个数据集,里面填充了SQL数据库中的约会数据,我有一个数据网格视图,它可以数据绑定到这个显示约会数据的数据集。
我的目标是创建一个数据视图,显示按时间排序的约会,然后迭代插入未使用约会时间的行的数据集,这些插入的行将仅在约会时间列中显示一个时间。
我已成功在数据集中插入一个新行,并在一个特定索引处使用一个按钮进行测试(索引最终将在一个预约时间的循环中确定找不到),datagridview用新行更新;但是,当我在添加新行后对数据进行排序时,它们都出现在datagridview的底部。
我知道排序的数据视图不代表实际的数据集顺序,所以我试图基于数据视图创建一个新的数据表,但我无法让它工作。
如果我尝试插入排序后的新行也不起作用。
有人可以帮忙吗?
这是我有代码
Hi All,
I'm having serious trouble with this so I'm hoping somebody can assist me.
I have a dataset which is filled with appointment data from an SQL database, I have a datagridview which is databound to this dataset which displays the appointment data.
My aim is to create a dataview which shows the appointments sorted by time, and then iterate through the dataset inserting rows where appointment times are not used, these inserted rows will show only a time in the Appointment Time column.
I have succeeded in inserting a new row in the dataset with an appointment time at a particular index using a button to test (index will eventually be determined in a loop where an appointment time is not located), the datagridview updates with the new row; However, when I sort the data after adding the new rows, they all appear at the bottom of the datagridview.
I understand that the sorted dataview is not representative of the actual dataset order, so I'm trying to create a new datatable based on the dataview but I just can't get it working.
Also if I try to insert a new row after sorting it doesn't work either.
Can anybody help?
Here's the code I have
private void UpdateAppointmentsDataGrid()
{
sdaAppointments = new SqlDataAdapter();
sdaAppointments.SelectCommand = cmd;
dbAppointmentsDataSet = new DataTable();
sdaAppointments.Fill(dbAppointmentsDataSet);
AppointmentsbSource = new BindingSource();
AppointmentsbSource.DataSource = dbAppointmentsDataSet;
dgvAppointments.DataSource = AppointmentsbSource;
sdaAppointments.Update(dbAppointmentsDataSet);
}
private void btnAddNewRow_Click(object sender, EventArgs e)
{
DataRow row = dbAppointmentsDataSet.NewRow();
dbAppointmentsDataSet.Rows.InsertAt(row, 3);
row[0] = DateTime.Now;
}
private void btnSort_Click(object sender, EventArgs e)
{
DataView newView = new DataView(dbAppointmentsDataSet);
newView.Sort = "Appointment Time";
DataTable newTable = newView.ToTable();
dgvAppointments.DataSource = newTable.DefaultView;
}
推荐答案
尝试直接绑定newView
Try directly binding newView
newView.sort = "Appointment Time asc";
dgvAppointments.DataSource = newView.ToTable();
这应该有用。
This should work.
这篇关于如何在插入新行后对数据集进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!