private DataSet ds = new DataSet();
DataTable dt = new DataTable();
private SqlDataAdapter dap = new SqlDataAdapter();
BindingSource bs = new BindingSource();
这是我调用数据库数据的方法:
public DataSet AccessDBData(string sqlString, string tableName)
{
try
{
using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["strConnection"]))
{
sqlconn.Open();
using (System.Data.SqlClient.SqlCommand odbCommand = new System.Data.SqlClient.SqlCommand())
{
odbCommand.Connection = sqlconn;
odbCommand.CommandText = sqlString;
dap.SelectCommand = odbCommand;
dap.Fill(ds, tableName);
}
sqlconn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ex.StackTrace);
}
return ds;
}
/// <summary>
/// 绑定数据到DataGridView
/// </summary>
private void BindDataToDataGridView()
{
string selectsql = string.Format("select * from {0}", DBModels.CoalVerifiedHole.TableName);
AccessDBData(selectsql, DBModels.CoalVerifiedHole.TableName);
bs.DataSource = ds.Tables[0];
dt = ds.Tables[0];
bindingNavigator1.BindingSource = bs;
dgv_CoalVerifiedHole.DataSource = bs;
dgv_CoalVerifiedHole.Columns["ID"].Visible = false;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("确定要保存吗?", "提示!", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
{
if (dap != null)
{
SqlCommandBuilder Sqlcb = new SqlCommandBuilder(dap);
dap.UpdateCommand = Sqlcb.GetUpdateCommand();
dap.InsertCommand = Sqlcb.GetInsertCommand();
dap.DeleteCommand = Sqlcb.GetDeleteCommand();
if (dap.Update(ds, DBModels.CoalVerifiedHole.TableName) != 0)
{
MessageBox.Show("保存成功!", "提示");
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但就是保存不进去!总是说 ConnectionString属性尚未初始化.弄了两天了,怎么调试都没用。求大神指教。