我有一个程序,基本上是创建,读取,编辑和删除linq数据库。它在不同的行上运行得很好,但是当我选择第一行删除它时,它就像没有选择row一样,所以它返回给我一个"选择行"输出警告。
另外,当我单击第一行上的modify时,它总是只编辑它下面的行。(其他行不受影响)
这是类中的'event update'代码:-
public int UpdateEvent(int selectedRow, string name, DateTime date, string eventType, string eventVenue)
{
EventTicketEntities database = new EventTicketEntities();
Event selected = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault(); //selected row will give the id of the row
if (selected == null)
{
return -1;
}
else
{
selected.EventName = name;
selected.EventDate = date;
selected.EventType = eventType;
selected.EventVenue = eventVenue;
return database.SaveChanges();
}
}
这是类中'事件删除'的代码:-
public int DeleteEvent(int selectedRow)
{
EventTicketEntities database = new EventTicketEntities();
Event eventDelete = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault();
database.Events.Remove(eventDelete); //We use this method to delete the particular customer
return database.SaveChanges(); //returns the affected rows ....
}
这是表单按钮的代码:-
private void btnModify_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.UpdateEvent(SelectedRow, eventName.Text, calendar.Value, cmbEventType.SelectedValue.ToString(), cmbEventVenue.SelectedValue.ToString());
MessageBox.Show(result + " rows affected!" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
else
{
EventBL eBL = new EventBL();
MessageBox.Show("Select Row first" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
这是删除按钮的代码:-
private void btnDelete_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.DeleteEvent(SelectedRow);
MessageBox.Show(result + " rows affected!");
dgvEvents.DataSource = eBL.GetEvents();
SelectedRow = -1;
}
}
else
{
MessageBox.Show("Select Row first");
}
}
数据网格视图的事件处理程序代码:-
private void dgvEvents_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > 0)
{
SelectedRow = int.Parse(dgvEvents[0, e.RowIndex].Value.ToString());
}
}
非常感谢你的帮助。
照顾-HurpaDerpa
顺便说一下,selected总是会得到一个不能为空的值所以条件是如果选择= = null)永远都是假的因为你赋值。firstdefault