导航

在GridView编辑行中绑定下拉框数据

Posted on 2010-06-19 15:37  ykhi  阅读(7919)  评论(2编辑  收藏  举报


.aspx代码:

代码
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
2 ForeColor="#333333" GridLines="None" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand">
3 <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
4 <Columns>
5 <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" />
6 <asp:TemplateField HeaderText="Sex">
7 <EditItemTemplate>
8 <asp:DropDownList ID="ddlSex" runat="server" Width="151px">
9 </asp:DropDownList>
10 </EditItemTemplate>
11 <ItemTemplate>
12 <asp:Label ID="lblSex" runat="server" Text='<%# Eval("Sex") %>'></asp:Label>
13 </ItemTemplate>
14 </asp:TemplateField>
15 <asp:TemplateField>
16 <EditItemTemplate>
17 &nbsp;
18 <asp:Button ID="btnCancel" runat="server" Text="取消" CommandName="C" />
19 </EditItemTemplate>
20 <ItemTemplate>
21 <asp:Button ID="btnEdit" runat="server" Text="编辑" CommandName="E"/>
22 </ItemTemplate>
23 </asp:TemplateField>
24 </Columns>
25 <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
26 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
27 <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
28 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
29 <AlternatingRowStyle BackColor="White" />
30 </asp:GridView>

.aspx.cs代码:

代码
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 if (!IsPostBack)
4 {
5 BindData();
6 }
7 }
8
9 private void BindData()
10 {
11 string strCon = "数据库连接字符串";
12 string strSql = "select UserName,Sex from tblUserDemo";
13
14 SqlDataAdapter da = new SqlDataAdapter(strSql, strCon);
15 DataTable dt = new DataTable();
16 da.Fill(dt);
17
18 this.GridView1.DataSource = dt;
19 this.GridView1.DataBind();
20
21 }
22 //数据绑定后触发
23   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
24 {
25 //如果行的类型是数据绑定行
26 if (e.Row.RowType == DataControlRowType.DataRow)
27 {
28 //行的状态是:正常状态 或者 交替行
29 if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
30 {
31 Label lblSex = e.Row.FindControl("lblSex") as Label;
32 if (lblSex != null)
33 {
34 if (lblSex.Text == "0")
35 {
36 lblSex.Text = "";
37 }
38 else
39 {
40 lblSex.Text = "";
41 }
42 }
43 }
44 //行的状态是: 编辑状态 或者 (交替行且是编辑状态)
45 if(e.Row.RowState == DataControlRowState.Edit ||
46 e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit))
47 {
48 DropDownList ddlSex = e.Row.FindControl("ddlSex") as DropDownList;
49 if (ddlSex != null)
50 {
51 ListItem item1 = new ListItem();
52 item1.Value = "0";
53 item1.Text = "";
54 ddlSex.Items.Add(item1);
55
56 ListItem item2 = new ListItem();
57 item2.Value = "1";
58 item2.Text = "";
59 ddlSex.Items.Add(item2);
60 }
61 }
62 }