我正在开发一个基本的游戏启动器,我遇到了如下所示的错误…当控件为数据绑定时,错误声明"无法以编程方式将行添加到DataGridView的行集合"。
我能做些什么来解决这个问题?
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
}
另一种形式的代码:
MainForm mainForm;
DataTable table;
public Form2(MainForm mf)
{
InitializeComponent();
this.mainForm = mf;
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Exe Files (.exe)|*.exe|All Files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtPath.Text = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
DataTable dataTable = (DataTable)dataGridView1.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd["Game"] = txtTitle;
drToAdd["Path"] = txtPath;
mainForm.dataGridView1.Rows.Add(drToAdd);
dataTable.AcceptChanges();
}
private void AddGame_Load(object sender, EventArgs e)
{
table = new DataTable();
table.Columns.Add("Game", typeof(string));
table.Columns.Add("Path", typeof(string));
dataGridView1.DataSource = table;
dataGridView1.Columns["Path"].Visible = false;
dataGridView1.Columns["Game"].Width = 138;
dataGridView1.ScrollBars = ScrollBars.None;
}
}
错误照片
考虑在子表单中定义一个事件,该事件将预期的数据传递给主表单。在下面的示例中,在DataGridView中预定义了两个列,每个列都设置了DataPropertyName。
MainForm
- 在load事件中设置一个硬连线数据表,通过BindingSource设置为DataGridView(这是可选的,但在许多方面使生活更容易)。
- 在一个按钮点击事件中显示子窗体,同时订阅一个事件来向DataGridView添加行。
public partial class MainForm : Form
{
private readonly BindingSource _bindingSource =
new BindingSource();
public MainForm()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
DataTable table = new DataTable();
table.Columns.Add("FirstName", typeof(string));
table.Columns.Add("LastName", typeof(string));
_bindingSource.DataSource = table;
dataGridView1.DataSource = _bindingSource;
}
private void ShowChildFormButton_Click(object sender, EventArgs e)
{
var childForm = new ChildForm();
childForm.AddPerson += OnAddPerson;
childForm.ShowDialog();
childForm.Dispose();
}
private void OnAddPerson(string firstname, string lastname)
{
((DataTable)_bindingSource.DataSource)
.Rows
.Add(firstname, lastname);
}
}
子窗体,如果两个文本框控件都不为空,则将值传递给MainForm。
public partial class ChildForm : Form
{
public delegate void OnAdd(string firstName, string lastName);
public event OnAdd AddPerson;
public ChildForm()
{
InitializeComponent();
}
private void PostButton_Click(object sender, EventArgs e)
{
if (
!string.IsNullOrWhiteSpace(FirstNameTextBox.Text) &&
!string.IsNullOrWhiteSpace(LastNameTextBox.Text))
{
AddPerson?.Invoke(FirstNameTextBox.Text, LastNameTextBox.Text);
}
}
}