如何根据SQL查询在gridview中添加标题列? ASP.NET C#

时间:2016-06-17 06:48:56

标签: c# asp.net gridview sql-server-2012

我有gridview。我想动态地在QUERY RESULT标题(列)中显示gridview。标题显示基于SQL-QUERY。 这是我的SQL-QUERY
USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='pak' 例如,它返回行idnamecity然后我想在gridview标题中显示这些节目。 我怎样才能做到这一点。 ASPX:

<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
    <form id="form" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" 
            onrowdatabound="GridView1_RowDataBound">
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" OnClick="load" Text="Button" />
    </form>
</asp:Content>

ASPX.CS

public void load(object sender, EventArgs e)
{
    //string tbl_name = Session["value"].ToString();
    //string tbl_name = "new";
    string query = "USE db_compiler SELECT Column_Name FROM tbl_field WHERE Table_Name='pak'";
    SqlCommand cmd = new SqlCommand(query, cnn);
    DataTable dt = new DataTable();
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataTable table = new DataTable();
    cnn.Open();
    cmd.ExecuteNonQuery();
    adp.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
    cnn.Close();
}

1 个答案:

答案 0 :(得分:1)

使用AutoGenerateColumns="true"时的默认行为是从数据源检索列名。如果没有显示列名,那么您的SQL查询可能有问题。以下代码工作正常:

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
        this.GetData();
}

private void GetData()
{
    var table = new DataTable();
    string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

    using (var connection = new SqlConnection(connectionString))
    {
        using (var command = new SqlCommand("SELECT ID, City FROM Cities", connection))
        {
            using (var a = new SqlDataAdapter(command))
            {
                connection.Open();
                a.Fill(table);
                connection.Close();
            }
        }
    }
   GridView1.DataSource = table;
   GridView1.DataBind();
}

<强> .ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>

<强>输出:

Dynamically display GridView column headers