C# 如何从GridView检索我的ProductID?
我试图从gridview检索我的ProductID,我试图使用此代码检索我的数据,但它给出了错误: 索引超出范围。必须为非负数且小于 收藏。参数名称:索引 这是我的代码:C# 如何从GridView检索我的ProductID?,c#,html,C#,Html,我试图从gridview检索我的ProductID,我试图使用此代码检索我的数据,但它给出了错误: 索引超出范围。必须为非负数且小于 收藏。参数名称:索引 这是我的代码: strProductId = GridView1.Rows[1].Cells[1].Text; 这就是原始gridview的外观 这是一个使用数据的示例 您没有解释如何寻找数据来源,但请看下面的示例代码,这将有助于您理清问题 using System; using System.Data; using System.Dat
strProductId = GridView1.Rows[1].Cells[1].Text;
这就是原始gridview的外观
这是一个使用数据的示例
您没有解释如何寻找数据来源,但请看下面的示例代码,这将有助于您理清问题
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());
}
}
}
}
错误消息是不言自明的。您的
DataGrid
既不包含两行也不包含两列。对于初学者来说,有一点额外的细节-C#中的集合(如代码行中的行和单元格)是基于零的。例如,要获取代码中的第一行,可以使用GridView1.Rows[0]。