How to add header columns based on data fetch from the database in gridview

笑着哭i 提交于 2019-12-13 04:22:41

问题


I have a GridView and want to make headers dynamically based on the some SQL query like...

select question from quiz where quizid is 123.

This query will return * number of questions based on the quizid.

How to create headers with the data that's been selected from database?


回答1:


You can use DataTable to help with this.

I don't know which technologies you used for database management, but I used LinQ to SQL. And the following is my sample:

DataClassesDataContext db = new DataClassesDataContext();

protected DataTable GetDataSource() 
{
    DataTable dt = new DataTable();

    var questions = db.ExecuteQuery<string>("select question from quiz where quizid is 123").ToList();

    // Header implementation
    int count = 0;
    foreach (var question in questions)
    {
        DataColumn dc = new DataColumn(question);
        dt.Columns.Add(dc);
        count++;
    }

    // Rows implementation here
    DataRow row = dt.NewRow();
    ...
    dt.Rows.Add(row);

    return dt;
}


protected void Page_Load(object sender, EventArgs e)
{
    GridView1.DataSource = GetDataSource();
    GridView1.DataBind();
}

And here is my aspx code:

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



回答2:


I will suggest you to Add HeaderText Dynamically on RowDataBound event. You could try something like

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{    
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       GridView.Columns[0].HeaderText = "New Header text for First Column";
    }
}

You could find RowDataBound on properties >> Events of GridView control. and RowDataBound fires on binding of every row of GridView.



来源:https://stackoverflow.com/questions/22294320/how-to-add-header-columns-based-on-data-fetch-from-the-database-in-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!