c# - 如何从 GridView 检索我的 ProductID?
问题描述
我正在尝试从 gridview 中检索我的 ProductID,我尝试使用此代码检索我的数据,但它给出了错误:
指数超出范围。必须是非负数且小于集合的大小。参数名称:索引
这是我的代码:
strProductId = GridView1.Rows[1].Cells[1].Text;
这就是原始网格视图的样子
这是一个使用数据的示例
解决方案
您没有解释如何获取数据,但请查看下面的示例代码,这应该可以帮助您理顺事情。
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());
}
}
}
}
推荐阅读
- javascript - 通过端口将事件处理程序从 elm 传递给 JS
- sparql - 使用本体 URI 最终出现“找不到错误 404”
- javascript - Is there a way to get a subset/section of a path in d3.js?
- amazon-web-services - Appsync:订阅数组中的元素
- node.js - 使用 --mount 标志时 Docker 容器不运行
- android - 为什么我的 onCreateView 中的 WebView 代码无法访问?
- python - 如何在绿龙渲染中获取剪辑距离和纹理
- python - 删除链表中所有重复的元素
- android - 错误:无法解决:com.github.imperiumlabs:GeoFirestore-Android:v1.5.0
- tensorflow - RGB图像上的Tensorflow conv2d