代码是从网上找的,不过拿来用发现还有那么些地方需要注意,我提一下。不对的地方请指出。
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=(local);user id= sa;pwd=;DataBase=pubs");
con.Open();
string strsql = "select * from sales";
SqlDataAdapter da = new SqlDataAdapter(strsql, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.HeaderRow.Cells.Clear();
TableCell cell = new TableCell();
cell.Text = "<tr><td rowspan='2'>年份</td><td rowspan='2'>供电所</td><td rowspan='2'>供电量(万KWh)</td><td rowspan='2'>售电量(万KWh)</td><td colspan='3'>损失电量(万KWh)</td><td colspan='3'>损失率(%)</td><td rowspan='2'>电费金额(元)</td><td rowspan='2'> 平均售电电价(元/千KWh)</td><td rowspan='2'>查看</td></tr><tr><td>高低压</td><td>高压</td><td>低压</td><td>高低压</td><td>高压</td> <td>低压</td> </tr>";
GridView1.HeaderRow.Cells.Add(cell);
}
其中cell.text这是从DW里直接把代码拷贝过来的,只是里面诸如字体或是样式设置都不能要了
补充一点:如果不是前期绑定了数据源的话,GridView的AutoGenerateColumns属性应该为True
代码很清楚,我这提醒的就是 应该先给GridView绑定数据,之后再添加表头,因为在绑定数据之前GridView的列头总是为Null !如果是先于绑定数据使用到HeaderRow,就会出现 未将对象引用设置到对象的实例这个错误提示!
这只是我自己的理解,如若谁看到代码的不妥或是该改进之处还望提出,大家一起学习!谢谢