从我的DataGridView获取值以在另一个表单上显示 - C#

时间:2015-03-29 15:29:48

标签: c# datagridview

基本上,当我点击单元格时,我希望能够让该行上的所有内容以另一种形式显示。

我在Show Form上有这个代码:

 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;
    }

}

在我的mainPage表单中名为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[column, row];因为我得到了IndexOutOfRange异常。此外,在调试时,它在'row'变量上说是-1。最后,触发事件需要我很长时间,有时我会多次按下单元格标题以使其工作。我不知道发生了什么事,任何可能来到我身边的灯都会非常感激。

亲切的问候,

基兰

2 个答案:

答案 0 :(得分:0)

试试这个..

 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1)
    {
        string value =  dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 
    }

}

答案 1 :(得分:0)

CellContentClick事件文档说:

  

单击单元格内容时会发生此事件

单元格内容仅指单元格的内容,而不是单元格中的空白空间。在这种情况下,你不会被解雇。

在您的上下文中,我会使用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)
    {

       ...... 
    }
}