在我的应用程序中,我有一个包含很多行的datagridview,很多用户会定期更新它。我想为它添加一个上下文菜单,使用户可以右键单击并从上下文菜单中选择编辑,然后它应该打开第二个包含所有选定行值的表单。
我使用以下代码
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
{
int editloannumber = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[0].Value.ToString());
int editlid = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[8].Value.ToString());
string editloantype = dataGridView1.Rows[oneCell.RowIndex].Cells[1].Value.ToString();
string editneworsecond = dataGridView1.Rows[oneCell.RowIndex].Cells[2].Value.ToString();
string editpurpose = dataGridView1.Rows[oneCell.RowIndex].Cells[11].Value.ToString();
string editstatus = dataGridView1.Rows[oneCell.RowIndex].Cells[3].Value.ToString();
string editcomments = dataGridView1.Rows[oneCell.RowIndex].Cells[7].Value.ToString();
string editretail = dataGridView1.Rows[oneCell.RowIndex].Cells[12].Value.ToString();
wartif_UW.editform e2 = new wartif_UW.editform(editloannumber, editloantype, editneworsecond, editpurpose, editstatus, editcomments, editretail,editlid);
e2.ShowDialog();
}
}
}
我将datagridview选择模式设置为fullrowselect,当我运行代码时,它加载我的第二个表单,但不仅仅是因为for循环而多次循环回来。我怎么能阻止这个?
当我将datagridview选择模式设置为cellselect时,它工作得很好。但我想选择所有行
编写点击功能我使用以下代码
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = dataGridView1.HitTest(e.X, e.Y);
if (hti.RowIndex >= 0)
{
dataGridView1.ClearSelection();
dataGridView1.CurrentCell =dataGridView1[hti.ColumnIndex,hti.RowIndex];
}
}
}
答案 0 :(得分:0)
让我们来看看你的for-loop
如果您有完整的行选择模式,那么您的单元格将始终被选中
所以if语句真的没有做任何事情
此外,所选单元格的RowIndex
将始终相同
那么为什么不用for-loop代替这样的东西:
if(dataGridView1.SelectedCells.Count > 0)
{
var oneCell = dataGridView1[0];
int editloannumber = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[0].Value.ToString());
int editlid = int.Parse(dataGridView1.Rows[oneCell.RowIndex].Cells[8].Value.ToString());
string editloantype = dataGridView1.Rows[oneCell.RowIndex].Cells[1].Value.ToString();
string editneworsecond = dataGridView1.Rows[oneCell.RowIndex].Cells[2].Value.ToString();
string editpurpose = dataGridView1.Rows[oneCell.RowIndex].Cells[11].Value.ToString();
string editstatus = dataGridView1.Rows[oneCell.RowIndex].Cells[3].Value.ToString();
string editcomments = dataGridView1.Rows[oneCell.RowIndex].Cells[7].Value.ToString();
string editretail = dataGridView1.Rows[oneCell.RowIndex].Cells[12].Value.ToString();
wartif_UW.editform e2 = new wartif_UW.editform(editloannumber, editloantype, editneworsecond, editpurpose, editstatus, editcomments, editretail,editlid);
e2.ShowDialog();
}