![](/img/trans.png)
[英]show the data from datagridview of one form to another form using c#
[英]Getting values from my DataGridView to show on another form - C#
基本上,当我单击单元格时,我希望能够使该行中的所有内容以另一种形式显示。
我的显示表单上有以下代码:
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表单中名为taskViewerDGV的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。 最后,触发事件花了我很多时间,有时我不得不多次按单元格标题才能使其起作用。 我不知道发生了什么事,任何能以我的方式出现的光都将不胜感激。
亲切的问候,
基兰
尝试这个..
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
string value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}
}
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)
{
......
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.