在我的项目中,有一个datagridview,如果没有数据,然后单击UPDATE按钮,我将得到错误消息。在这里,如果我直接单击update按钮,我将得到错误消息,但是如果我单击datagridview (即使在datagridview中没有数据)并单击update,我将得到更新后的消息。请告诉我应该使用什么代码来代替(dataGridView2.SelectedCells.Count == 0)。我使用的代码是:
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dataGridView2.SelectedCells.Count == 0)
{
MessageBox.Show("There are no any records to update");
}
else
{
SqlConnection con = Helper.getconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandType = CommandType.Text;
string PrjName = txtPrjNmae.Text;
string Description = txtPrjdescription.Text;
DateTime Date = dateUpdate.Value;
dateUpdate.Format = DateTimePickerFormat.Custom;
dateUpdate.CustomFormat = "dd/MM/yy";
string Size = txtPrjSize.Text;
string Manager = txtPrjManager.Text;
cmd.CommandText = "Update Projects set Description='" + Description + "', DateStarted='" + Date + "',TeamSize='" + Size + "',Manager='" + Manager + "' where ProjectName= '" + PrjName + "' ";
MessageBox.Show("Project Details are updated");
dataGridView2.Update();
dataGridView2.Refresh();
cmd.ExecuteNonQuery();
con.Close();
}
BindData3();
} 发布于 2013-10-09 07:36:08
我认为这里的问题是您将DataGridView的DataGridView属性设置为true。这样,DataGridView的底部总是有一个空行,所以RowCount将返回几乎1(用于创建新条目的空行)。
要解决这个问题,几乎有两种可能性:
AllowUserToAddRows设置为false。
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dataGridView2.SelectedCells.Count == 0 || dataGridView2.RowCount <= 1)
{
MessageBox.Show("There are no any records to update");
}
else
{
SqlConnection con = Helper.getconnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandType = CommandType.Text;
string PrjName = txtPrjNmae.Text;
string Description = txtPrjdescription.Text;
DateTime Date = dateUpdate.Value;
dateUpdate.Format = DateTimePickerFormat.Custom;
dateUpdate.CustomFormat = "dd/MM/yy";
string Size = txtPrjSize.Text;
string Manager = txtPrjManager.Text;
cmd.CommandText = "Update Projects set Description='" + Description + "', DateStarted='" + Date + "',TeamSize='" + Size + "',Manager='" + Manager + "' where ProjectName= '" + PrjName + "' ";
MessageBox.Show("Project Details are updated");
dataGridView2.Update();
dataGridView2.Refresh();
cmd.ExecuteNonQuery();
con.Close();
}
BindData3();
} 希望这能有所帮助。
发布于 2013-09-24 09:46:01
试试这个:
if (dataGridView2.RowCount == 0){
MessageBox.Show("There are no any records to update");
}发布于 2013-09-25 05:34:19
尝试使用以下代码并查看它是否有效:
dataGridView2.RowCount == 0https://stackoverflow.com/questions/18977350
复制相似问题