C# 如何将从sql查询的多行值添加到cmd中
我有下面的代码。SQL查询返回两行值。 但是,当我涉及方法C# 如何将从sql查询的多行值添加到cmd中,c#,sql,sql-server,asp-classic,C#,Sql,Sql Server,Asp Classic,我有下面的代码。SQL查询返回两行值。 但是,当我涉及方法cmd.ExecuteReader()时应用程序仅返回第一行值 我如何着手解决这个问题?cmd.Parameters.AddWithValue方法是否有问题?请帮忙 sqlQuery = "select name, data,data2 from surgicalfiledemo where id = '2'"; SqlCommand cmd = new SqlCommand(sqlQuery, con); cmd.Parameters.
cmd.ExecuteReader()时代码>应用程序仅返回第一行值
我如何着手解决这个问题?cmd.Parameters.AddWithValue
方法是否有问题?请帮忙
sqlQuery = "select name, data,data2 from surgicalfiledemo where id = '2'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("id", surgicalGridView.SelectedRow.Cells[1].Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + dr["name"].ToString() + ".xls");
HttpContext.Current.Response.ContentType = "application/excel";
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(dr["data"] + "\t");
Response.Write(dr["data2"] + "\t");
Response.End();
}
如果使用命令参数,则必须在查询中使用@
参数:
将Id='2'
更改为Id=@Id
,然后在添加值时将“Id”
更改为@Id
试试这个:
sqlQuery = "select name, data,data2 from surgicalfiledemo where id = @id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("@id", surgicalGridView.SelectedRow.Cells[1].Text);
//SqlDataReader dr = cmd.ExecuteReader(); use sqldata adapter to load all the data then fill to to Datatable and Bind it on GridView
SqlDataAdapter adapt = new SqlDataAdapter();
DataTable dt = new DataTable();
adapt.SelectCommand = cmd;
adapt.Fill(dt);
GridView GridView1 = new GridView();
GridView1.DataSource = dt;
GridView1.DataBind();
// if (dr.Read()) { .. } this causes you to return single record only, your export to excel execute every time a row was read thats why you can only see one record.
Response.Clear();
Response.Buffer = true;
string filename="MyExportedData.xls";
Response.AddHeader("content-disposition","attachment;filename="+filename);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
检查此链接:
向您问好是的!但是应用程序仍然返回一行值。如何更改代码以使应用程序返回一行值?c#新手!surgicalGridView.SelectedRow.Cells[1].Text的值是多少?您是否可以将dr.read()代码添加到surgicalGridview.SelectedRow.Cells[1]的值中。Text=我可以通过下载链接下载excel文件的行。明白了。您的代码所做的是,当读卡器读取每一行时,它实际上只显示一行,因为导出到excel的内容也在您读取的代码中。因此,我应该如何更改代码?有什么例子可以说明吗?谢谢如果您获得多行数据,则需要使用while(dr.Read()){……}
代码片段循环它们。现在-您只从数据读取器读取一行。。。。