我正在使用Microsoft Visual C#2008 Express Edition創建此項目。 我想插入數據使用單選按鈕如何編寫代碼例如,我想插入性別(男性/女性)。請幫我寫的代碼如何使用C#在Access中創建,更新和刪除數據?
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con;
DataSet ds1;
OleDbDataAdapter da;
int MaxRows = 0;
int inc = 0;
private void Form1_Load(object sender, EventArgs e)
{
con = new.OleDbConnection();
ds1 = new DataSet();
con.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/MyWorkers1.mdb";
string sql = "SELECT * from tblWorkers";
da = new OleDbDataAdapter(sql, con);
con.Open();
da.Fill(ds1, "MyWorkers1");
NavigateRecords();
MaxRows = ds1.Tables["MyWorkers1"].Rows.Count;
//MaxRows = ds1.Tables["MyWorkers1"].Rows[inc];
//MessageBox.Show("Database open");
con.Close();
//MessageBox.Show("Database close");
con.Dispose();
}
private void NavigateRecords()
{
DataRow drow = ds1.Tables["MyWorkers1"].Rows[inc];
textBox1.Text = drow.ItemArray.GetValue(0).ToString();
textBox2.Text = drow.ItemArray.GetValue(1).ToString();
textBox3.Text = drow.ItemArray.GetValue(2).ToString();
}
private void btnNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateRecords();
}
else
{
MessageBox.Show("No More Records");
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (inc > 0)
{
inc--;
NavigateRecords();
}
else
{
MessageBox.Show("First Record");
}
}
private void btnFirst_Click(object sender, EventArgs e)
{
if (inc != 0)
{
inc = 0;
NavigateRecords();
}
}
private void btnLast_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc = MaxRows - 1;
NavigateRecords();
}
}
private void btnAddNew_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
}
private void btnSave_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);
DataRow drow = ds1.Tables["MyWorkers1"].NewRow();
drow[0] = textBox1.Text;
drow[1] = textBox2.Text;
drow[2] = textBox3.Text;
ds1.Tables["MyWorkers1"].Rows.Add(drow);
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
da.Update(ds1, "MyWorkers1");
MessageBox.Show("Record/Entry Added");
}
}
}
當運行這個它顯示da.Update錯誤(DS1, 「MyWorkers1」);`喜歡
無效OperationException未處理的連接屬性尚未intialized
請幫幫我。
爲什麼你把OleDbCommandBuilder放在btnSave_click事件中? – Prokurors 2013-09-24 14:17:03
好吧,我知道了...這是如此「直觀」:( – Prokurors 2013-09-24 14:31:11