C# 用户控件与窗体之间传值
用户自定义控件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public partial class GirdViewUserControl : DevExpress.XtraEditors.XtraUserControl { public event EventHandler MyKeyDown; public event EventHandler MyDoubleClick; public GirdViewUserControl() { InitializeComponent(); MyGridView.AttributeConfig(this.gridControl1, this.gridView1); this.gridView1.KeyDown += gridView1_KeyDown; this.gridView1.DoubleClick += gridView1_DoubleClick; } void gridView1_DoubleClick(object sender, EventArgs e) { if (MyDoubleClick != null) { DataRow row = this.gridView1.GetFocusedDataRow(); if (row != null) { MyDoubleClick(row, e); } else { MyDoubleClick(null, e); } } } void gridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (MyKeyDown != null) { DataRow row = this.gridView1.GetFocusedDataRow(); if (row != null) { MyKeyDown(row, e); } else { MyKeyDown(null, e); } } } } /// <summary> /// 返回GridControl对象 /// </summary> public GridControl MMCGridControl { get { return this.gridControl1; } } /// <summary> /// 返回用户选择行索引 int[] /// </summary> public int[] GetSelectIndex { get { return this.gridView1.GetSelectedRows(); } } /// <summary> /// 返回用户选择所有行,List /// </summary> /// <returns>DataRow</returns> public List<DataRow> GetDataRow() { List<DataRow> List = new List<DataRow>(); foreach (int arr in GetSelectIndex) { List.Add(this.gridView1.GetDataRow(arr)); } return List; } }
窗体
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
readonly GridControl gconList = null; gconList = this.girdViewUserControl1.MMCGridControl; this.girdViewUserControl1.MyKeyDown += girdViewUserControl1_OnKeyDown; this.girdViewUserControl1.MyDoubleClick += new EventHandler(girdViewUserControl1_MyDoubleClick); void girdViewUserControl1_OnKeyDown(object sender, EventArgs e) { if(sender!=null) { DataRow dr = sender as DataRow; if(dr!=null) { XtraMessageBox.Show(dr["jobtitle"].ToString(), "显示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } void girdViewUserControl1_MyDoubleClick(object sender, EventArgs e) { if (sender != null) { DataRow dr = sender as DataRow; if (dr != null) { XtraMessageBox.Show(dr[1].ToString(), "显示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } private void button1_Click(object sender, EventArgs e) { List<DataRow> list = this.girdViewUserControl1.GetDataRow(); System.Text.StringBuilder strbui = new System.Text.StringBuilder(); foreach (DataRow dr in list) { strbui.AppendFormat(",{0}", dr[2]); } XtraMessageBox.Show(strbui.ToString().Substring(1), "显示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); }