一直以来都被这个问题困扰,但是由于手头工作太多,也就没管它,不过这几天随着系统功能的需要,问题变得突出了,不得不寻求解决方案。在网上搜到一种方法,通过使用BindingManagerBase,获取当前的绑定状态。
BindingManagerBase bmb;
bm=this.BindingContext[this.dgdCalendar.DataSource,this.dgdCalendar.DataMember];
DataRow row=((DataRowView)bmb.Current).Row;
再通过上面的代码就可以获得当前行了。
但是我的程序主要是想通过右键来获取某个单元格的数据,这样的话,上面的方法就不适用了。我想了一个比较笨的方法,就是先利用一个DataTable将当前的DataGrid 中的数据复制一份,然后再通过HitTestInfo取到当前的行列,然后就可以在前面的数据拷贝中获得需要的数据了。 事实上我下面的代码比上面说的更复杂,因为我的DataGrid还有一些隐藏列,而我在右键点击时,这些隐藏列也要获取,所以就有了下面的代码。
DataTable dtCalendar=(DataTable)this.dgdCalendar.DataSource;
//将当前表格中的数据暂存
DataTable dtGridCopy=dtCalendar.Clone();
for(int i=0;i<dtCalendar.Rows.Count;i++)
{
DataRow row=dtGridCopy.NewRow();
row["A"]=this.dgdCalendar[i,0].ToString();
row["B"]=this.dgdCalendar[i,2].ToString();
row["C"]=this.dgdCalendar[i,3].ToString();
dtGridCopy.Rows.Add(row);
}
//与数据源比对,映射各个列值
for(int i=0;i<dtCalendar.Rows.Count;i++)
{
for(int j=0;j<dtGridCopy.Rows.Count;j++)
if(dtCalendar.Rows[i]["A"].ToString()==dtGridCopy.Rows[j]["A"].ToString() &&
dtCalendar.Rows[i]["B"].ToString()==dtGridCopy.Rows[j]["B"].ToString() &&
dtCalendar.Rows[i]["C"].ToString()==dtGridCopy.Rows[j]["C"].ToString()
)
{
dtGridCopy.Rows[i]["D"]=dtCalendar.Rows[j]["D"];
dtGridCopy.Rows[i]["E"]=dtCalendar.Rows[j]["E"];
}
}

浙公网安备 33010602011771号