可能重复:
从 c#.net 添加记录以访问数据库时出错
我需要使用下面的代码向 Access 数据库添加一条新记录,但我得到了一个IndexOutOfRangeException
. 我试图解决它,但我找不到解决方案。我应该如何克服这个错误?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
System.Data.OleDb.OleDbConnection con;
DataSet ds1;
System.Data.OleDb.OleDbDataAdapter da;
int MaxRows = 0;
int inc = 0;
private void Form2_Load(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
ds1 = new DataSet();
con.ConnectionString ="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:/Users/JaYam/Documents/jaya.accdb";
string sql = "SELECT * From Table1";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
con.Open();
da.Fill(ds1, "Table1");
NavigateRecords();
con.Close();
con.Dispose();
}
private void NavigateRecords()
{
DataRow drow =ds1.Tables["Table1"].Rows[0];
textBox1.Text = drow.ItemArray.GetValue(0).ToString();
textBox2.Text = drow.ItemArray.GetValue(1).ToString();
textBox3.Text = drow.ItemArray.GetValue(2).ToString();
textBox4.Text = drow.ItemArray.GetValue(3).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
ds1 = new DataSet();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/JaYam/Documents/jaya.accdb";
string sql = "SELECT * From Table1";
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
con.Open();
da.Fill(ds1, "Table1");
NavigateRecords();
System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);
DataRow dRow = ds1.Tables["Table1"].NewRow();
//dRow[0] = textBox1.Text;
dRow[1] = textBox2.Text;
dRow[2] = textBox3.Text;
dRow[3] = textBox4.Text;
dRow[4] = textBox4.Text;
ds1.Tables["Table1"].Rows.Add(dRow);
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
da.Update(ds1, "Table1");
MessageBox.Show("Entry Added");
con.Close();
con.Dispose();
}
}
}