当我调试这个程序时,我通过表单添加数据,并通过下一个和上一个按钮检查数据。表单显示数据,但是当我通过服务器资源管理器打开数据库并检查数据时,数据库中没有数据。我已多次这样做了。
注意:我尝试更改COPY TO OUTPUT DIRECTORY
属性,但没有帮助。我还在表格中添加了一些数据。
public partial class Form1 : Form
{
DatabaseConnection objConnect;
string conString;
DataSet ds;
DataRow dRow;
int MaxRows;
int inc = 0;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
objConnect = new DatabaseConnection();
conString = Properties.Settings.Default.Employees1ConnectionString;
objConnect.Connection_string = conString;
objConnect.Sql = Properties.Settings.Default.SQL;
ds = objConnect.Getconnection;
MaxRows = ds.Tables[0].Rows.Count;
NavigateRecords();
}
catch (Exception err)
{
MessageBox.Show(err.Message,"Error");
}
}
private void NavigateRecords()
{
dRow = ds.Tables[0].Rows[inc];
txtFirstname.Text = dRow.ItemArray.GetValue(1).ToString();
txtSurname.Text = dRow.ItemArray.GetValue(2).ToString();
txtJobtitle.Text = dRow.ItemArray.GetValue(3).ToString();
txtDepartment.Text = dRow.ItemArray.GetValue(4).ToString();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("No more rows!");
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (inc > 0)
{
inc--;
NavigateRecords();
}
else
{
MessageBox.Show("First Record!");
}
}
private void btnaddnew_Click(object sender, EventArgs e)
{
txtFirstname.Clear();
txtSurname.Clear();
txtJobtitle.Clear();
txtDepartment.Clear();
btnaddnew.Enabled = false;
btnsave.Enabled = true;
btnCancel.Enabled = true;
}
private void btnsave_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
row[1] = txtFirstname.Text;
row[2] = txtSurname.Text;
row[3] = txtJobtitle.Text;
row[4] = txtDepartment.Text;
ds.Tables[0].Rows.Add(row);
try
{
objConnect.Updatedatabase(ds);
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
MessageBox.Show("Database has been updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
btnaddnew.Enabled = true;
btnsave.Enabled = false;
btnCancel.Enabled = false;
}
private void btnCancel_Click(object sender, EventArgs e)
{
NavigateRecords();
btnaddnew.Enabled = true;
btnsave.Enabled = false;
btnCancel.Enabled = false;
}
}` class DatabaseConnection
{
private string sql_string;
private string strCon;
SqlDataAdapter da_1;
public string Sql
{
set { sql_string = value; }
}
public string Connection_string
{
set { strCon = value; }
}
public DataSet Getconnection
{
get { return MyDataSet(); }
}
public DataSet MyDataSet()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
public void Updatedatabase(DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}