![](/img/trans.png)
[英]How to Get select row data of gridview into dropdown list and textboxes
[英]How to get gridview all checked row data into textboxes of another form in C#?
我有一個數據網格視圖,其中復選框列為第一列。 我們想要的是當用戶選中行時,所有選中的行都應轉到另一個“表單”中的文本框。 我寫了以下文章。 但是問題是盡管檢查了多於1行,但總是將最后檢查的行數據發送到下一個表單。 並非所有選中的行數據
private void btngnvoucher_Click(object sender, EventArgs e)
{
// foreach(DataGridViewRow row in dataGridView1.Rows)
for (int x = 0; x < dataGridView1.RowCount;x++ )
{
// DataGridViewCheckBoxCell ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
DataGridViewCheckBoxCell ch1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[x].Cells[0];
if (ch1.Value != null)
{
for (int a = 0; a < 6; a++)
{
for (int col = 1; col < 5; col++)
{
TextBox theText1 = (TextBox)vobj.Controls[col - 1];
// theText1.Text = row[x].Cells[col].Value.ToString();
theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();
}
// a = a + 1;
break;
}
}
}
vobj.Show();
}
}
}
誰能告訴我該如何解決?
代替這個:
theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();
嘗試:
theText1.AppendText(dataGridView1.Rows[x].Cells[col].Value.ToString());
問題的原因似乎是您打算讓變量a
進行某些操作,但不對其執行任何操作。 看起來這意味着要引用一行文本框,然后由在單元格上方查看的代碼填充這些文本框。
按照目前的代碼:
for (int col = 1; col < 5; col++)
{
TextBox theText1 = (TextBox)vobj.Controls[col - 1];
// theText1.Text = row[x].Cells[col].Value.ToString();
theText1.Text = dataGridView1.Rows[x].Cells[col].Value.ToString();
}
為每一行填充相同的四個文本框。
就是說,您的代碼還有很多其他問題,這些問題在修復后可能會使您更清楚。
首先-盡可能使用foreach循環遍歷DataGridView
的行和單元格集合。 最終,它變得更加干凈和易於維護。 例如,當您遍歷所需的列時,您假定永遠不會添加另一列。
接下來-嘗試通過名稱而不是索引來引用列。 維護代碼時它不那么脆弱。
您查看復選框是否被選中的檢查是不正確的-如果用戶先選中該復選框然后再刪除該支票,您的處理方式將仍然計數。 您需要檢查是否為null,如果不為null,則檢查true。
通過這些更改,您將獲得以下內容:
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["CheckBox"].Value != null && (bool)r.Cells["CheckBox"].Value)
{
foreach (DataGridViewCell c in r.Cells)
{
if (c.ValueType == typeof(string))
{
// The code here is still ugly - there is almost certainly
// a better design for what you are trying to do but that is
// beyond the scope of the question.
// Plus it still has your original bug of referencing the
// same row of text boxes repeatedly.
TextBox theText1 = (TextBox)vobj.Controls[c.ColumnIndex];
theText1 += c.Value.ToString();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.