我有一个gridview但目前它只设置一个标题。我想要它做的是根据用户数在表格末尾的其他列旁边添加新标题。
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView1.UseAccessibleHeader = true;
GridView1.AutoGenerateColumns = false;
int i = 6;
string constr = ConfigurationManager.ConnectionStrings["CMT"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
GridView1.Columns[6].HeaderText = sdr["user_first_name"].ToString();
break;
}
}
conn.Close();
}
}
}
}
答案 0 :(得分:0)
您可以在绑定数据之前将TemplateField
列添加到GridView。它可以在Page_Load
事件处理程序中完成:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM [user]";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
TemplateField field = new TemplateField();
field.HeaderText = sdr["user_first_name"].ToString();
field.HeaderStyle.Width = Unit.Pixel(80);
GridView1.Columns.Add(field);
}
}
conn.Close();
}
}
}
}