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?
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
.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.