![](/img/trans.png)
[英]How to get values from selected row in DataGrid for Windows Form Application?
[英]How to get values from selected row in DataGrid?
我發現的所有內容都是關於DataGridView
,並嘗試了一些事件處理程序,現在我陷入了困境。
假設我有如下的DataGrid:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Code", typeof(String));
dt.Columns.Add("Name", typeof(String));
gridData.DataSource = dt;
我如何使用SelectedRows["ID"]
捕獲onClick
事件
此解決方案適用於DataGridView
但不適用於DataGrid。
您可以使用該DataGrid的屬性SelectedCells
。 該屬性返回給您當前選定單元格的集合,您可以使用foreach
循環遍歷該集合
假設您希望以字符串形式獲取值,則此代碼可能會有用:
// This is the list where the values will be stored. Now it's empty.
List<string> values = new List<string>();
// Whit this 'foreach' we iterate over 'gridData' selected cells.
foreach (DataGridCellInfo x in gridData.SelectedCells)
{
// With this line we're storing the value of the cells as strings
// in the previous list.
values.Add(x.Item.ToString());
}
然后,您可以稍后在onClick()
方法中使用存儲的值。
您可以看到以下Microsoft MSDN網站:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.