如何在消息框中获取DataGridView单元格的值?

22

在C#中,我该如何获取DataGridView单元格的值并将其写入MessageBox中?

8个回答

28
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
    {
       MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
    }
}

25

您可以使用DataGridViewCell.Value属性来检索特定单元格中存储的值。

因此,要检索“第一个”选定单元格中的值并在消息框中显示,您可以执行以下操作:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

以上可能并不完全是您需要做的。如果您提供更多细节,我们可以提供更好的帮助。


谢谢!但是你告诉我的已经足够了,解决了我的问题 :) - Brezhnews
MessageBox.Show(dataGridView1.SelectedCells[0].Value?.ToString()); - Xarylem

17
MessageBox.Show(" Value at 0,0" + DataGridView1.Rows[0].Cells[0].Value );

5
      try
        {

            for (int rows = 0; rows < dataGridView1.Rows.Count; rows++)
            {

                for (int col = 0; col < dataGridView1.Rows[rows].Cells.Count; col++)
                {
                    s1 = dataGridView1.Rows[0].Cells[0].Value.ToString();
                    label20.Text = s1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("try again"+ex);
        }

4
   private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(Convert.ToString(dataGridView1.CurrentCell.Value));
    }

有些晚了,但希望能对你有所帮助。


3
我在数据表格的“按钮”中添加了以下代码,以获取用户单击的行中单元格的值:
string DGCell = dataGridView1.Rows[e.RowIndex].Cells[X].Value.ToString();

在我这里,Datagrid列数是从1而不是从0开始计数。如果不确定是datagrid的默认设置还是因为我使用SQL填充信息导致的,请将X替换为您想要检查的单元格。


2
求和所有单元格
        double X=0;
        if (datagrid.Rows.Count-1 > 0)
        {
           for(int i = 0; i < datagrid.Rows.Count-1; i++)
            {
               for(int j = 0; j < datagrid.Rows.Count-1; j++)
               {
                  X+=Convert.ToDouble(datagrid.Rows[i].Cells[j].Value.ToString());
               }
            } 
        }

1
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
           int rowIndex = e.RowIndex; // Get the order of the current row 
            DataGridViewRow row = dataGridView1.Rows[rowIndex];//Store the value of the current row in a variable
            MessageBox.Show(row.Cells[rowIndex].Value.ToString());//show message for current row
    }

2
嗨 @سعد الضبي,你能在这个代码块周围添加一些注释吗? - Stuart.Sklinar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接