我正在尝试从gridview检索我的ProductID,我尝试使用此代码来检索我的数据,但它给出了错误:
索引超出范围。必须为非负数且小于 集合。参数名称:索引
这是我的代码:
strProductId = GridView1.Rows[1].Cells[1].Text;
这是原始gridview的外观
这是数据的外观示例
答案 0 :(得分:0)
您没有说明如何采购数据,而是查看下面的示例代码,这将有助于您弄清一切。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
SqlConnection connection;
SqlDataAdapter adapter;
SqlCommandBuilder cmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
string Sql;
Int32 i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
Sql = "select * from Product";
try
{
connection.Open();
adapter = new SqlDataAdapter(Sql, connection);
adapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
cmdBuilder = new SqlCommandBuilder(adapter);
changes = ds.GetChanges();
if (changes != null)
{
adapter.Update(changes);
}
MessageBox.Show("Changes Done");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
也。 。
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string connetionString;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
DataSet ds = new DataSet();
DataSet changes;
int i;
string Sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
Sql = "select * from tblUsers";
try
{
connection.Open();
oledbAdapter = new OleDbDataAdapter(Sql, connection);
oledbAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
changes = ds.GetChanges();
if (changes != null)
{
oledbAdapter.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Save changes");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}