Reputation: 719
I have the following piece of code. The SQL query returns me two rows of value.
However, when I involve the method cmd.ExecuteReader();
the application only returns the first row of values.
How do I go about resolving this? Is it something wrong with the cmd.Parameters.AddWithValue
method? Please help!
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();
}
Upvotes: 0
Views: 246
Reputation: 6130
If you are using command parameters you must use @
parameter on your query:
Change Id='2'
to Id=@Id
then and on your add with value "id"
change it to @Id
.
Try this:
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();
Check this link : ASP.NET: Export Grid View to Excel
Best Regards
Upvotes: 1