从datareader填充gridview

编程入门 行业动态 更新时间:2024-10-24 10:16:00
本文介绍了从datareader填充gridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

大家好, 我开发了一个桌面应用程序,我想生成一个SqlDataReader来填充gridview。 是类

Hello guys, I developed a desktop application and I want to generate a SqlDataReader to fill the gridview. the is class

class operation{ SqlConnection con = new SqlConnection(Connection.connectionString); SqlCommand com = new SqlCommand(); public SqlDataReader rd; public SqlDataReader getdata(string query) { com.CommandText = query; com.Connection = con; con.Open(); rd = com.ExecuteReader(); con.Close(); return rd; } }

和生成按钮

and the button to generate

private void button2_Click(object sender, EventArgs e) { oper.getdata("Select * From Customers"); rd = oper.rd; if (rd.HasRows) { while (rd.Read()) { } } con.Close(); }

我有很多错误。我希望能找到答案。 非常感谢!

I have a lot of errors. I hope to find the answer. Thanks a lot!

推荐答案

Hi Please试试这个 Hi Please try this protected void button2_Click(object sender, EventArgs e) { SqlDataReader sqlDataReader = GetData(query, conString);//conString is Connection String }

和'GetData'方法如下

And 'GetData' method is as below

public SqlDataReader GetData(string queryString, string connectionString) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader reader = command.ExecuteReader(); SqlDataReader sqlDataReader = reader; DataTable dataTable = new DataTable(); dataTable.Columns.Add("Customer Id"); dataTable.Columns.Add("Customer Name"); while (sqlDataReader.Read()) { DataRow row = dataTable.NewRow(); row["Customer Id"] = sqlDataReader["CustomerId"]; row["Customer Name"] = sqlDataReader["CustomerName"]; dataTable.Rows.Add(row); } GridView1.DataSource = dataTable; GridView1.DataBind(); connection.Close(); return reader; }

希望它会有所帮助。尝试后将问题标记为已解决。 - 谢谢

Hope it will helpful. Mark question as solved after trying. -- Thanks

SqlDataReader对象允许您以快进方式读取数据方式。调用SqlDataReader的Close方法以确保没有任何资源泄漏。 SqlDataReader objects allow you to read data in a fast forward-only manner. Call the Close method of the SqlDataReader to ensure there are not any resource leaks. private void BindGrid() { string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select * from Customers"; cmd.Connection = con; con.Open(); DataGridView1.DataSource = cmd.ExecuteReader(); con.Close(); } } }

更多推荐

从datareader填充gridview

本文发布于:2023-05-31 10:05:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/389550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:datareader   gridview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!