14
2015
06

【C#、Asp.Net 工具类大全】GridView 绑定数据及操作大全工具类

前端页面代码:

<style type="text/css">
    #DataList1 { border:solid 1px #ff0000; width:600px;}
    #GridView1 { border:solid 1px #00ff00; margin-top:10px; width:600px;}
    .Repeater { border:solid 1px #0000ff; margin-top:5px; width:600px;}
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" GridLines="None"
    UseAccessibleHeader="False" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="站点">
            <ItemTemplate>
                <asp:Label ID="UserSite" runat="server" Text='<%#Bind("UserSite") %>'></asp:Label>
            </ItemTemplate>
            <ItemStyle HorizontalAlign="Center"/>
        </asp:TemplateField>
        <asp:BoundField DataField="UserName" HeaderText="姓名" />
        <asp:BoundField DataField="UserAge" HeaderText="年龄" />
        <asp:BoundField DataField="UserSex" HeaderText="性别" />
    </Columns>
</asp:GridView>

使用C#实例:

private DataTable dt = new DataTable();
private DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        #region 基础数据
        dt = new DataTable();
        dt.Columns.Add("UserName");
        dt.Columns.Add("UserAge");
        dt.Columns.Add("UserSex");
        dt.Columns.Add("UserSite");
        DataRow dr = dt.NewRow();
        dr["UserName"] = "郑德才";
        dr["UserAge"] = "27";
        dr["UserSex"] = "男";
        dr["UserSite"] = "http://www.zhengdecai.com";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["UserName"] = "旺旺";
        dr["UserAge"] = "29";
        dr["UserSex"] = "女";
        dr["UserSite"] = "http://www.zhengdecai.cn";
        dt.Rows.Add(dr);
        dv = new DataView(dt);
        #endregion
        gridViewInfo();
    }
}
/// <summary>
/// GridView操作
/// </summary>
private void gridViewInfo()
{
    BindDataHelper.BindGridView(GridView1, dv);
    //GridViewHelper.GroupRows(GridView1, 0);
    //GridViewHelper.GroupRowsCount(GridView1, 0);
    GridViewHelper.MergeRows(GridView1, 0, "UserSite");

    DataTable dtG = GridViewHelper.GridView2DataTable(GridView1);
    string[] s = new string[2] { "UserName", "UserSite" };
    DataTable dtL1 = GridViewHelper.ToDataTable<User>(uL);
    DataTable dtL2 = GridViewHelper.ToDataTable<User>(uL, s);
}
/// <summary>
/// 绑定的GridView操作(合并单元格等)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //首先判断是否是数据行
    if (e.Row.RowType == DataControlRowType.DataRow)
    { 
        if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
        {
            TableCell tc0 = e.Row.Cells[0];
            TableCell tc2 = e.Row.Cells[2];
            GridViewHelper.SetCellText(tc0, 5);
            string age = GridViewHelper.GetCellText(tc2);
        }
    }
}

类库信息:

/// <summary>
/// GridView 绑定数据及操作大全
/// </summary>
public class GridViewHelper
{
    #region 私有方法
    /// <summary>
    /// 截取内容长度
    /// </summary>
    /// <param name="o_Str">原字符串</param>
    /// <param name="len">截取长度</param>
    /// <returns>截取后字符串</returns>
    public static string GetStrPartly(string o_Str, int len)
    {
        if (len == 0)
        {
            return o_Str;
        }
        else
        {
            if (o_Str.Length > len)
            {
                return o_Str.Substring(0, len) + "..";
            }
            else
            {
                return o_Str;
            }
        }
    }
    /// <summary>
    /// 获取单元格内容
    /// </summary>
    /// <param name="cell">TableCell</param>
    /// <returns>内容</returns>
    public static string GetCellText(TableCell cell)
    {
        string text = cell.Text;
        if (!string.IsNullOrEmpty(text))
        {
            return text;
        }
        foreach (Control control in cell.Controls)
        {
            if (control != null && control is IButtonControl)
            {
                IButtonControl btn = control as IButtonControl;
                text = btn.Text.Replace("\r\n", "").Trim();
                break;
            }
            if (control != null && control is ITextControl)
            {
                LiteralControl lc = control as LiteralControl;
                if (lc != null)
                {
                    continue;
                }
                ITextControl l = control as ITextControl;
                text = l.Text.Replace("\r\n", "").Trim();
                break;
            }
        }
        return text;
    }
    /// <summary>
    /// 设置单元格内容
    /// </summary>
    /// <param name="cell">TableCell</param>
    /// <param name="maxLen">最大长度</param>
    public static void SetCellText(TableCell cell, int maxLen)
    {
        string text = cell.Text;
        if (!string.IsNullOrEmpty(text))
        {
            cell.Text = GetStrPartly(text, maxLen);
        }
        foreach (Control control in cell.Controls)
        {
            if (control != null && control is IButtonControl)
            {
                IButtonControl btn = control as IButtonControl;
                text = btn.Text.Replace("\r\n", "").Trim();
                btn.Text = GetStrPartly(text, maxLen);
                break;
            }
            if (control != null && control is ITextControl)
            {
                LiteralControl lc = control as LiteralControl;
                if (lc != null)
                {
                    continue;
                }
                ITextControl l = control as ITextControl;
                text = l.Text.Replace("\r\n", "").Trim();
                if (l is DataBoundLiteralControl)
                {
                    cell.Text = GetStrPartly(text, maxLen);
                    break;
                }
                else
                {
                    l.Text = GetStrPartly(text, maxLen);
                    break;
                }
            }
        }
    }
    #endregion
    #region 公有方法
    /// <summary>
    /// 从GridView的数据生成DataTable
    /// </summary>
    /// <param name="gv">GridView对象</param>
    public static DataTable GridView2DataTable(GridView gv)
    {
        DataTable table = new DataTable();
        int rowIndex = 0;
        List<string> cols = new List<string>();
        if (!gv.ShowHeader && gv.Columns.Count == 0)
        {
            return table;
        }
        GridViewRow headerRow = gv.HeaderRow;
        int columnCount = headerRow.Cells.Count;
        for (int i = 0; i < columnCount; i++)
        {
            string text = GetCellText(headerRow.Cells[i]);
            cols.Add(text);
        }
        foreach (GridViewRow r in gv.Rows)
        {
            if (r.RowType == DataControlRowType.DataRow)
            {
                DataRow row = table.NewRow();
                int j = 0;
                for (int i = 0; i < columnCount; i++)
                {
                    string text = GetCellText(r.Cells[i]);
                    if (!String.IsNullOrEmpty(text))
                    {
                        if (rowIndex == 0)
                        {
                            string columnName = cols[i];
                            if (String.IsNullOrEmpty(columnName))
                            {
                                continue;
                            }
                            if (table.Columns.Contains(columnName))
                            {
                                continue;
                            }
                            DataColumn dc = table.Columns.Add();
                            dc.ColumnName = columnName;
                            dc.DataType = typeof(string);
                        }
                        row[j] = text;
                        j++;
                    }
                }
                rowIndex++;
                table.Rows.Add(row);
            }
        }
        return table;
    }
    /// <summary>
    /// 将集合类转换成DataTable
    /// </summary>
    /// <param name="list">集合</param>
    public static DataTable ToDataTable(IList list)
    {
        DataTable result = new DataTable();
        if (list.Count > 0)
        {
            PropertyInfo[] propertys = list[0].GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                result.Columns.Add(pi.Name, pi.PropertyType);
            }
            for (int i = 0; i < list.Count; i++)
            {
                ArrayList tempList = new ArrayList();
                foreach (PropertyInfo pi in propertys)
                {
                    object obj = pi.GetValue(list[i], null);
                    tempList.Add(obj);
                }
                object[] array = tempList.ToArray();
                result.LoadDataRow(array, true);
            }
        }
        return result;
    }
    /// <summary>
    /// 将泛型集合类转换成DataTable
    /// </summary>
    /// <typeparam name="T">集合项类型</typeparam>
    /// <param name="list">集合</param>
    /// <param name="propertyName">需要返回的列的列名</param>
    /// <returns>数据集(表)</returns>
    public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
    {
        List<string> propertyNameList = new List<string>();
        if (propertyName != null) propertyNameList.AddRange(propertyName);
        DataTable result = new DataTable();
        if (list.Count > 0)
        {
            PropertyInfo[] propertys = list[0].GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                if (propertyNameList.Count == 0)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
                else
                {
                    if (propertyNameList.Contains(pi.Name)) result.Columns.Add(pi.Name, pi.PropertyType);
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                ArrayList tempList = new ArrayList();
                foreach (PropertyInfo pi in propertys)
                {
                    if (propertyNameList.Count == 0)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                    }
                }
                object[] array = tempList.ToArray();
                result.LoadDataRow(array, true);
            }
        }
        return result;
    }
    #endregion
    #region
    /// <summary>
    /// 合并BoundField绑定列
    /// </summary>
    /// <param name="gv">需要合并GridView</param>
    /// <param name="cellNum">第几列</param>
    public static void GroupRows(GridView gv, int cellNum)
    {
        int i = 0, rowSpanNum = 1;
        while (i < gv.Rows.Count - 1)
        {
            GridViewRow gvr = gv.Rows[i];
            for (++i; i < gv.Rows.Count; i++)
            {
                GridViewRow gvrNext = gv.Rows[i];
                if (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text)
                {
                    gvrNext.Cells[cellNum].Visible = false;
                    rowSpanNum++;
                }
                else
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                    rowSpanNum = 1;
                    break;
                }
                if (i == gv.Rows.Count - 1)
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                }
            }
        }
    }
    /// <summary>
    /// 合并指定相同列的单元格,并显示合并列数
    /// </summary>
    /// <param name="gv">需要合并GridView</param>
    /// <param name="cellNum">第几列</param>
    public static void GroupRowsCount(GridView gv, int cellNum)
    {
        int i = 0, rowSpanNum = 1;
        while (i < gv.Rows.Count)
        {
            GridViewRow gvr = gv.Rows[i];
            for (++i; i < gv.Rows.Count; i++)
            {
                GridViewRow gvrNext = gv.Rows[i];
                if (gvr.Cells[cellNum].Text == gvrNext.Cells[cellNum].Text)
                {
                    gvrNext.Cells[cellNum].Visible = false;
                    rowSpanNum++;
                }
                else
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                    gvr.Cells[cellNum].Text = gvr.Cells[cellNum].Text + "(" + rowSpanNum + ")";
                    rowSpanNum = 1;
                    if (gvrNext.Cells[cellNum].Text != "" && i == gv.Rows.Count - 1)
                    {
                        gvrNext.Cells[cellNum].Text = gvrNext.Cells[cellNum].Text + "(" + rowSpanNum + ")";
                    }
                    break;
                }
                if (i == gv.Rows.Count - 1)
                {
                    gvr.Cells[cellNum].RowSpan = rowSpanNum;
                    gvr.Cells[cellNum].Text = gvr.Cells[cellNum].Text + "(" + rowSpanNum + ")";
                }
            }
        }
    }
    /// <summary> 
    /// 合并行(合并的列要用Label控件) 
    /// </summary> 
    /// <param name="gvw">需要合并的GridView</param> 
    /// <param name="sCol">要合并的列(从0开始)</param> 
    /// <param name="controlName">控件名称</param> 
    public static void MergeRows(GridView gvw, int col, string controlName)
    {
        for (int rowIndex = gvw.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow row = gvw.Rows[rowIndex];
            GridViewRow previousRow = gvw.Rows[rowIndex + 1];
            Label row_lbl = row.Cells[col].FindControl(controlName) as Label;
            Label previousRow_lbl = previousRow.Cells[col].FindControl(controlName) as Label;
            if (row_lbl != null && previousRow_lbl != null)
            {
                if (row_lbl.Text == previousRow_lbl.Text)
                {
                    row.Cells[col].RowSpan = previousRow.Cells[col].RowSpan < 1 ? 2 : previousRow.Cells[col].RowSpan + 1;
                    previousRow.Cells[col].Visible = false;
                }
            }
        }
    }
    #endregion
}

显示效果:

以上类库内容来源互联网,站长稍作整理

« 上一篇下一篇 »

评论列表:

1.范超博客  2015/6/17 14:45:38 回复该留言
感谢分享
2.火锅桌椅  2015/6/17 17:35:48 回复该留言
感谢分享。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。