asp.net GridView绑定到数组,用数组绑定到GridView
前台:
后台:
下边的例子是从数据库里取出值,把值用split分割后在转成数组的形式绑定到GridView
前台
后台
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true">
- <Columns>
- <asp:BoundField DataField="id12333" HeaderText="id"/>
- </Columns>
- </asp:GridView>
后台:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- }
- }
- void BindGridView()
- {
- this.GridView1.DataSource = GetTable();
- this.GridView1.DataBind();
- }
- DataTable GetTable()
- {
- DataTable dt = new DataTable();
- dt.Columns.Add("id12333", typeof(string));
- string[] str = new string[3];//把这个数组改成你的就好了
- str[0] = "11111111";
- str[1] = "2222";
- str[2] = "3333";
- for (int i = 0; i < str.Length; i++)
- {
- str[i] = str[i].ToString();
- }
- for (int j = 0; j < str.Length; j++)
- {
- DataRow row = dt.NewRow();
- row["id12333"] = str[j];
- dt.Rows.Add(row);
- }
- return dt;
- }
下边的例子是从数据库里取出值,把值用split分割后在转成数组的形式绑定到GridView
前台
- <asp:GridView ID = "gvwQXLB" AutoGenerateColumns = "False" Width = "100%" runat = "server" Height="100%">
- <Columns>
- <asp:TemplateField HeaderText="选择">
- <ItemTemplate>
- <asp:CheckBox ID="ckbYHQX" runat="server" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField DataField="bodfViewYHQX_menucaption" HeaderText="用户权限"/>
- <asp:BoundField DataField="bodfViewQXLB_qxlb" HeaderText="权限类别"/>
- </Columns>
- </asp:GridView>
后台
- #region GridView绑定数据,显示用户权限
- /// <summary>
- /// GridView绑定数据,显示用户权限
- /// </summary>
- private void gvwBind()
- {
- DataSet ds = new DataSet();
- DataTable dt = new DataTable();
- dt.Columns.Add("bodfViewYHQX_menucaption", typeof(string));
- dt.Columns.Add("bodfViewQXLB_qxlb", typeof(string));
- Model.userInfo.UserKey modelQXFP = new Model.userInfo.UserKey();
- BLL.userInfo.UserKey bllQXFP = new BLL.userInfo.UserKey();
- string yhmc;
- yhmc = Request.QueryString["yhmc"];
- ds = (DataSet)bllQXFP.get_YHQXXX(yhmc);
- string[] bodfViewYHQX_menucaption = new string[ds.Tables["dzjc.dzjc_yhqx"].Rows.Count];//开辟数组空间
- string[] bodfViewQXLB_qxlb = new string[ds.Tables["dzjc.dzjc_yhqx"].Rows.Count];
- for (int i = 0; i < ds.Tables["dzjc.dzjc_yhqx"].Rows.Count; i++)
- {
- bodfViewYHQX_menucaption = bllQXFP.get_YHQXXX(yhmc).Tables["dzjc.dzjc_yhqx"].Rows[i]["MENUCAPTION"].ToString().Split(',');//MENUCAPTION中数据格式个,“aa,bb,ccc,d,eeee,”
- bodfViewQXLB_qxlb[i] = Convert.ToString(bllQXFP.get_YHQXXX(yhmc).Tables["dzjc.dzjc_yhqx"].Rows[i]["qxlb"]);
- }
- for (int j = 0; j < bodfViewYHQX_menucaption.Length - 1; j++)//获得bodfViewYHQX_menucaption数组长度减一,因为MENUCAPTION中数据存储格式为“aa,bb,ccc,d,eeee,”,最后一个字符为“,”,所以要给长度减一
- {
- DataRow row = dt.NewRow();
- row["bodfViewYHQX_menucaption"] = bodfViewYHQX_menucaption[j];//把分割出来放到数组里的字符串放到DataRow里
- row["bodfViewQXLB_qxlb"] = bodfViewQXLB_qxlb[0];//同一个用户的权限类别相同,所以取下标为0的数组
- dt.Rows.Add(row);
- }
- gvwQXLB.DataSource = dt;//绑定到数组
- gvwQXLB.DataBind();
- ds.Dispose();
- }
- #endregion