[英]Getting data from selected datagridview row and which event?
我在 windows 表單上有一個 DataGridView(Selectionmode:FullRowSelect)和一些文本框,所以我想做的是,每當用戶選擇一行(可能單擊或雙擊)時,該行的內容必須顯示在文本中箱子,
我試過這段代碼:
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("CEll Double_Click event calls");
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
textBox5.Text = row.Cells[1].Value;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
textBox5.Text = dataGridView1.Rows[1].Cells[1].Value.ToString();// row.Cells[1].Value;
}
還有許多其他文本框,但主要問題是似乎沒有任何事件被觸發,我應該使用什么事件來觸發,或者是否有我可能設置錯誤的數據網格屬性? 任何幫助,將不勝感激...:(
您可以使用SelectionChanged事件,因為您使用的是FullRowSelect選擇模式。 在處理程序內部,您可以訪問SelectedRows屬性並從中獲取數據。 例:
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView.SelectedRows)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
//...
}
}
您還可以遍歷列集合而不是鍵入索引...
您可以嘗試此點擊事件
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
Name_txt.Text = row.Cells["First Name"].Value.ToString();
Surname_txt.Text = row.Cells["Last Name"].Value.ToString();
首先拿一個標簽。 將其可見性設置為false,然后在DataGridView_CellClick事件上寫入此內容
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
// then perform your select statement according to that label.
}
//try it it might work for you
你應該檢查你的設計師文件。 打開Form1.Designer.cs和
找到這一行:windows Form Designer生成的代碼。
展開這個,你會看到很多代碼。 因此,如果沒有放置它,請檢查datagridview1控件內是否存在此行。
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
我希望它有所幫助。
簡單的解決方案如下。 這是來自谷的解決方案的改進。
private void dgMapTable_SelectionChanged(object sender, EventArgs e)
{
int active_map=0;
if(dgMapTable.SelectedRows.Count>0)
active_map = dgMapTable.SelectedRows[0].Index;
// User code if required Process_ROW(active_map);
}
請注意其他讀者,上面的代碼應該使用FullRowSelect
選擇模式的datagridview。 如果選擇了兩行以上,您可以擴展它以給出消息。
您可以使用 SelectionChanged 事件。 CurrentRow.DataBoundItem 將給出綁定項。
SelectionMode 屬性應為整行 select。
var item = ([CastToBindedItem])dataGridLocations.CurrentRow.DataBoundItem; tbxEditLocation.Text = item.Name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.