C#用listview以表格样子显示出了数据库信息,选中一条数据后,右键删除,总出现未将对象引用设置到对象实例
privatevoid删除ToolStripMenuItem_Click(objectsender,EventArgse){if(listView1.SelectedIt...
private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0)
{
MessageBox.Show("您没有选择任何用户", "操作提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
DialogResult choice = MessageBox.Show("确定要删除该用户吗?", "操作警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (choice == DialogResult.Yes )
{
int result = 0;
try
{
string sql = string.Format("delete from Customer where ID ={0} ",(int)this.listView1.SelectedItems[0].Tag);
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
result = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DBHelper.connection.Close();
}
if (result < 1)
{
MessageBox.Show("删除失败!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
MessageBox.Show("删除成功!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
fill();
}
} 展开
{
if (listView1.SelectedItems.Count == 0)
{
MessageBox.Show("您没有选择任何用户", "操作提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
DialogResult choice = MessageBox.Show("确定要删除该用户吗?", "操作警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (choice == DialogResult.Yes )
{
int result = 0;
try
{
string sql = string.Format("delete from Customer where ID ={0} ",(int)this.listView1.SelectedItems[0].Tag);
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open();
result = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DBHelper.connection.Close();
}
if (result < 1)
{
MessageBox.Show("删除失败!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
MessageBox.Show("删除成功!", "操作结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
fill();
}
} 展开
3个回答
展开全部
语句虽然写的不是很流畅,可是整个逻辑都没有问题,要是出错唯一的问题有可能是
string sql = string.Format("delete from Customer where ID ={0} ",(int)this.listView1.SelectedItems[0].Tag);
有可能(int)this.listView1.SelectedItems[0].Tag 为null或者转换错误,建议你将这个绑定看下是不是给Tag有值,还是将ID直接写进了该行的Text,
另外最好不要用这种转换,最好用int.Prase();
最后在在该语句中不需要将ID转换为INT型,可以直接赋值。比如
string sql = string.Format("delete from Customer where ID ='{0}' ",this.listView1.SelectedItems[0].Tag.tostring());
string sql = string.Format("delete from Customer where ID ={0} ",(int)this.listView1.SelectedItems[0].Tag);
有可能(int)this.listView1.SelectedItems[0].Tag 为null或者转换错误,建议你将这个绑定看下是不是给Tag有值,还是将ID直接写进了该行的Text,
另外最好不要用这种转换,最好用int.Prase();
最后在在该语句中不需要将ID转换为INT型,可以直接赋值。比如
string sql = string.Format("delete from Customer where ID ='{0}' ",this.listView1.SelectedItems[0].Tag.tostring());
追问
对啊!this.listView1.SelectedItems[0].Tag的值为null啊!但是为什么会这样啊?该怎么解决??
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询