我编写了用于在aspx的网页上显示sql查询内容的代码,我需要在网页上编辑返回结果的列名。以下是显示内容的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace XYZ
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["ABC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
string queryString = "select * from asde";
SqlCommand cmd = new SqlCommand(queryString,con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
SqlDataReader reader;
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
}
}
}
非常感谢编辑列名的任何指针
答案 0 :(得分:0)
您无法将datareader设置为网格数据源。数据适配器也应该使用关联的sql命令进行初始化。
您可以执行以下操作
SqlCommand cmd = new SqlCommand("select * from asde", con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapater(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
or
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();