我遇到了一個非常奇怪的問題,動態構建DataGridView和一組單選按鈕。我有一組單選按鈕和一個Panel中的DataGridView。我遇到的問題是我試圖使用某些單選按鈕上的事件處理函數來獲取DataGridView中的行數。我使用的DataTable有3行。您可以手動將問題重新添加到DGV中,這並不重要。當我打電話rows.count後,我將其初始化工作按計劃進行,並返回3,但是當一個事件處理程序被觸發行計數恢復爲0.我的代碼如下DataGridView中:DataGridView行數0事件處理程序後
private DataSet testData;
private DataTable testDataTable;
public Form1(API _api)
{
InitializeComponent();
api = _api;
businessLayer = new BusinessLayer();
testData = api.getDataSet();
testDataTable = businessLayer.getDataTable(testData);
buildDataGridView();
}
// Build the DataGridView
private void buildDataGridView()
{
int numOfRows = testDataTable.Rows.Count;
DataGridView testDataGridView = new DataGridView();
testDataGridView.Columns.Add("Description", "");
testDataGridView.Columns.Add("Name", "");
testDataGridView.Rows.Add(numOfRows);
testDataGridView.Location = new Point(150, 20);
for (int i = 0; i < numOfRows; i++)
{
RadioButton rbutton = new RadioButton();
rbutton.Name = testDataTable.Rows[i].Field<string>("Name").ToString() + "RadioButton";
rbutton.Text = testDataTable.Rows[i].Field<string>("Name");
rbutton.Tag = testDataTable.Rows[i].Field<string>("SortOrder");
rbutton.CheckedChanged += rbutton_CheckedChanged;
if (i == 0)
{
rbutton.Checked = true;
}
rbutton.Location = new Point(5, 20 * (i + 1));
testPanel.Controls.Add(definition);
}
testPanel.Controls.Add(testDataGridView);
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
// RadioButton CheckChanged EventHandler
private void definition_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if(rb.Checked)
{
textBox1.Text = testDataGridView.Rows.Count.ToString();
}
}
這真的讓我困惑,但如果我弄清楚,我一定會在這裏學到一些東西。我不知道這是否與DGV和單選按鈕位於面板內部有關,我不知道......感謝任何幫助,並幫助我學習!
'... laborLevelsDataGridView ... testDataGridView ...' – Steve
錯字...忘了將labviewLevelDataGridView的實例重命名爲testDataGridView。如果您重新命名laborLevels進行測試,您會看到我描述的行爲仍然存在 – waltmagic