ASP.NET动态生成GridView的使用

来源:互联网 发布:highlight.js下载 编辑:程序博客网 时间:2024/05/22 13:49
根据DataTable动态生成包含checkbox的GridView,其中DataTable中对应checkbox那一列的值必须为bool值。

public static GridView DynamicGenerateColumns(GridView gv, DataTable dt)        {            // 把GridView的自动产生列设置为false,否则会出现重复列            gv.AutoGenerateColumns = false;            // 清空所有的Columns            gv.Columns.Clear();            // 遍历DataTable 的每个Columns,然后添加到GridView中去            foreach (DataColumn item in dt.Columns)            {                if (item.ColumnName == "选择")                {                    CheckBoxField chCol = new CheckBoxField();                    chCol.HeaderText = item.ColumnName;                    chCol.DataField = item.ColumnName;                    chCol.Visible = true;                    gv.Columns.Add(chCol);                    continue;                }                BoundField col = new BoundField();                col.HeaderText = item.ColumnName;                col.DataField = item.ColumnName;                col.Visible = true;                gv.Columns.Add(col);            }            return gv;        }

然后在返回的GridView上绑定dataTable就可以了。还可以添加checkBox点击事件javascript处理函数。

gridView.DataSource = dataTable;gridView.DataBind();for (int i = 0; i < ChargingGridView.Rows.Count; i++){       ((System.Web.UI.WebControls.CheckBox)(gridView.Rows[i].Cells[0].Controls[0])).Attributes.Add("onclick", "OnClickCheck()");}

在JS函数中对GridView中checkbox的处理,注意下面的Javascript代码是如何获取checkbox及其它普通元素的的值。

//该函数实现了根据选择的checkbox计算某列的值总和的功能function OnClickCheck() {    var sumValue=0;    var gv = document.getElementById("<%=gridView.ClientID%>");    for (var i = 1; i < gv.rows.length; i++) {        if (gv.rows[i].cells[0].children[0].checked == false) {            continue;        }        sumValue = sumValue + parseFloat(gv.rows[i].cells[5].innerText);    }    document.getElementById('<%=TotalLabel.ClientID%>').innerHTML = sumValue;}

上面的代码在后端用C#实现如下,

private void OnClickCheck(){    double totalAmount = 0;    for (int i = 0; i < gridView.Rows.Count; i++)    {        if (false == ((System.Web.UI.WebControls.CheckBox)(ChargingGridView.Rows[i].Cells[0].Controls[0])).Checked)        {            continue;        }        totalAmount += Convert.ToDouble(gridView.Rows[i].Cells[6].Text.Trim());    }    TotalLabel.Text = totalAmount.ToString();}

SQL SERVER中bool的字段类型为bit,如果bool值是从DataTable取出的,则不用修改,如果该列bool值是在select返回的结果上添加的一列固定值,那么就需要在返回的DataTable前添加一列:

dataTable.Columns.Add("选择", typeof(bool));dataTable.Columns["选择"].SetOrdinal(0);foreach (DataRow dr in ChargeItemDataTable.Rows){       dr["选择"] = true;//初始化checkbox为选中}

关于在select返回的结果添加一列固定值,如果添加这一列是字符串或数值类型,那么直接在select语句中即可设置,如select '吴宗宪' as hostName,age from showhosts。但如果是bool值的话,就不能select true as 选择……,这样SQL会报错,要照上面的方法来添加。

现在还有个问题,就是生成的GridView中的checkbox是灰色的,不能操作,也就是enable为false。现在需要绑定GridView_RowDataBound函数,在该函数中设置checkBox的enabled为true。添加该函数过程为:在aspx页面设计页中,选中GridView,右边属性栏中选择事件,在下面找到RowDataBound,生成事件处理函数。

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e){     if (e.Row.Cells[0].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))     {           TableCell tc = e.Row.Cells[0];           if (tc.Controls.Count > 0)           {                System.Web.UI.WebControls.CheckBox cb = (System.Web.UI.WebControls.CheckBox)tc.Controls[0];                if (!(cb == null))                {                        cb.Enabled = true;                }           }      }}

有时候需要把GridView转换成DataTable:

public static DataTable GetDataTableFromGridView(GridView gv, DataTable dt){    GridViewRow headerRow = gv.HeaderRow;    int columnCount = headerRow.Cells.Count;    for (int i = 0; i < columnCount; i++)    {        DataColumn dc = dt.Columns.Add();        dc.ColumnName = headerRow.Cells[i].Text.Trim();        if ("选择" == headerRow.Cells[i].Text.Trim())        {            dc.DataType = typeof(bool);        }        else        {            dc.DataType = typeof(string);        }    }    for (int i = 0; i < gv.Rows.Count; i++)    {        DataRow dr = dt.NewRow();        for (int j = 0; j < gv.Columns.Count; j++)        {            if ("选择" == headerRow.Cells[j].Text.Trim())            {                if (true == ((System.Web.UI.WebControls.CheckBox)(gv.Rows[i].Cells[j].Controls[0])).Checked)                {                    dr[j] = true;                }                else                {                    dr[j] = false;                }            }            else if (gv.Rows[i].Cells[j].Text.Trim() == "&nbsp;")            {                dr[j] = "";            }            else            {                dr[j] = gv.Rows[i].Cells[j].Text.Trim();            }        }        dt.Rows.Add(dr);    }    return dt;}

 

0 0
原创粉丝点击