本文介绍了从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
发布评论