我有一个基本上从linq数据库创建,读取,编辑和删除的程序。 它确实在不同的行上运行良好,但是当我选择第一行来删除它时,它就好像没有选择ROW所以它返回一个"选择行"输出警告。
另外,当我点击第一行的修改时,它总是只编辑它下面的行。 (其他行不受影响)
这是事件更新'类中的代码: -
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
答案 0 :(得分:0)
顺便说一句,选中将始终获得一个不能为null的值 所以条件 如果(选择== null) 永远都是假的 因为您指定.firstordefault