C# 从我的DataGridView获取值以显示在另一个表单-C上
基本上,当我单击单元格时,我希望能够以另一种形式显示该行中的所有内容 我的展示表格上有以下代码:C# 从我的DataGridView获取值以显示在另一个表单-C上,c#,datagridview,C#,Datagridview,基本上,当我单击单元格时,我希望能够以另一种形式显示该行中的所有内容 我的展示表格上有以下代码: public partial class showTask : Form { public string TaskID, TaskName, TaskDescription, TaskTimeAndDateCompletion; public int TaskPriority; public showTask() { InitializeCompo
public partial class showTask : Form
{
public string TaskID, TaskName, TaskDescription, TaskTimeAndDateCompletion;
public int TaskPriority;
public showTask()
{
InitializeComponent();
}
public void ShowTaskChosen()
{
showTaskIDRtb.Text = TaskID;
showTaskNameRtb.Text = TaskName;
showTaskDescRtb.Text = TaskDescription;
showTaskPriorityRtb.Text = Convert.ToString(TaskPriority);
showTaskTimeAndCompletionDate.Text = TaskTimeAndDateCompletion;
}
}
在我的主页表单中名为tasksViewerDGV的DataGridView上,我要尝试获取要在另一个表单上显示的值:
private void tasksViewerDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int column = e.ColumnIndex;
int row = e.RowIndex;
DataGridView ShowTask = sender as DataGridView;
if (ShowTask == null)
return; //If the cell is null, then just return without sending any information
var cell = ShowTask[column, row];
if (cell != null)
{
DataGridViewRow rows = cell.OwningRow; //Which ever cell is clicked, it gets the row of that cell
showTask displayTask = new showTask();
displayTask.TaskID = rows.Cells["taskID"].Value.ToString();
displayTask.TaskName = rows.Cells["taskName"].Value.ToString();
displayTask.TaskDescription = rows.Cells["taskDescription"].Value.ToString();
displayTask.TaskPriority = Convert.ToInt32(rows.Cells["taskPriority"].Value.ToString());
displayTask.TaskTimeAndDateCompletion = rows.Cells["taskTimeAndDateCompletion"].Value.ToString();
displayTask.ShowDialog();
displayTask.ShowTaskChosen();
}
}
问题是:var cell=ShowTask[列,行];当我得到IndexOutfrange例外时。此外,在调试时,在“row”变量上显示s-1。最后,触发事件需要花费我很多时间,有时我必须多次按下单元格标题才能使其正常工作。我不知道发生了什么事,任何能照到我身上的光线都将不胜感激
亲切问候,
基兰试试这个
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
string value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}
}
活动文档说:
单击单元格内容时发生此事件
但是单元格内容只是指单元格的内容,而不是单元格中的一些空白。在这种情况下,不会触发事件
在你的上下文中,我会使用CellMouseClick
但是,如果单击网格的行标题或列标题,也会引发此事件。对于这些情况,行或列索引为-1
在尝试使用这些行和列的无效值查找网格单元之前,应该对它们进行某种保护
private void dgv_CellClickMouse(object sender,
DataGridViewCellMouseEventArgs e)
{
DataGridView dgv = sender as DataGridView;
int column = e.ColumnIndex;
int row = e.RowIndex;
if(column == -1 || row == -1)
{
// for debug purpose...
Console.WriteLine("Not a valid row/column");
return;
}
DataGridViewCell cell = dgv[column, row];
if (cell != null)
{
......
}
}
你用哪种方法获得上面的代码?@Steve我已经更新了上面的代码,这能回答你的问题吗嗨,我试过了,但不幸的是,我遇到了同样的问题。谢谢你的帮助!