在C#中,我该如何获取DataGridView单元格的值并将其写入MessageBox中?
在C#中,我该如何获取DataGridView单元格的值并将其写入MessageBox中?
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());
}
}
您可以使用DataGridViewCell.Value属性来检索特定单元格中存储的值。
因此,要检索“第一个”选定单元格中的值并在消息框中显示,您可以执行以下操作:
MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
以上可能并不完全是您需要做的。如果您提供更多细节,我们可以提供更好的帮助。
MessageBox.Show(" Value at 0,0" + DataGridView1.Rows[0].Cells[0].Value );
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);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show(Convert.ToString(dataGridView1.CurrentCell.Value));
}
有些晚了,但希望能对你有所帮助。
string DGCell = dataGridView1.Rows[e.RowIndex].Cells[X].Value.ToString();
在我这里,Datagrid列数是从1而不是从0开始计数。如果不确定是datagrid的默认设置还是因为我使用SQL填充信息导致的,请将X替换为您想要检查的单元格。
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());
}
}
}
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
}