问题
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