我正在从 mysql 表中填充 gridview
public void Init()
{
DataSet dataset = new DataSet();
dataset = FillGrid();
bindingSorce.DataSource = dataset.Tables[0];
gridControl1.DataSource = bindingSorce;
}
public static DataSet FillGrid()
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
try
{
DataSet dataset = new DataSet();
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataset);
}
else
{
return null;
}
newConnection.Close();
return dataset;
}
catch { return null; }
}
在进行任何更改后,我正在尝试更新 mysql 表
private void gridView1_RowUpdated(object sender, EventArgs e)
{
try
{
BindingSource bs = (BindingSource)gridView1.DataSource;
DataTable changes = ((DataTable)bs.DataSource).GetChanges();
if (changes != null)
{
bool asd = UpdateGrid(changes);
((DataTable)((BindingSource)gridView1.DataSource).DataSource).AcceptChanges();
}
}
catch { }
}
public static bool UpdateGrid(DataTable datatable)
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
//try
{
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cmb = new MySqlCommandBuilder(adapter);
//adapter.UpdateCommand = cmb.GetUpdateCommand();
//adapter.Update(datatable);
cmb.GetUpdateCommand();
adapter.Update(datatable);
}
else
{
return false;
}
newConnection.Close();
return true;
}
// catch { return false; }
}
并且表确实在更新,但是如果在那之后我将调用 Init() 那么 FillGrid() 将返回具有正确列但没有行的数据集!(dataset.tables[0].Rows.count = 0)。重启后程序填充将起作用,但再次更新将具有相同的效果