日期:2014-05-17 浏览次数:20565 次
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" DataKeyNames="roomno" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False" > <Columns> <asp:BoundField HeaderText="房间号" DataField="roomno" /> <asp:TemplateField HeaderText="房间类型" > <%--//如何绑定到字段--%> <ItemTemplate> <asp:DropDownList ID="roomtype" runat="server" > <asp:ListItem Value="1">豪华房</asp:ListItem> <asp:ListItem Value="2">商务房</asp:ListItem> <asp:ListItem Value="3">双人房</asp:ListItem> <asp:ListItem Value="4">房型4</asp:ListItem> <asp:ListItem Value="5">房型5</asp:ListItem> <asp:ListItem Value="6">房型6</asp:ListItem> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="roomstatu" HeaderText="房间状态" /> <asp:BoundField HeaderText="房价" DataField="unitprice" DataFormatString="{0:c}" /> <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> </Columns> </asp:GridView> .cs protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { int index = e.RowIndex;//当前选择行索引值 string roomno = GridView1.DataKeys[index].Value.ToString();//获取主键房间号 string roomtype = ((TextBox)(GridView1.Rows[index].Cells[1].Controls[0])).Text.Trim(); string roomstatu = ((TextBox)(GridView1.Rows[index].Cells[2].Controls[0])).Text.Trim(); string unitprice = ((TextBox)(GridView1.Rows[index].Cells[3].Controls[0])).Text.Trim(); string sql = "update room set roomtype="+roomtype+",roomstatu="+roomstatu+",unitprice="+unitprice+"";//更新语句 SqlConnection conn = new SqlConnection(strCon); conn.Open(); SqlCommand comm = new SqlCommand(sql, conn); int ret = comm.ExecuteNonQuery(); if (ret>0) { //更新成功 } else { //更新失败 } GridView1.EditIndex = -1; DataBind(); } catch (Exception ex) { throw; } } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int index = e.RowIndex; string roomno = GridView1.DataKeys[index].Value.ToString(); string sql = "delete from room where roomno="+roomno+"";//删除语句 SqlConnection conn = new SqlConnection(strCon); conn.Open(); SqlCommand comm = new SqlCommand(sql, conn); conn.Close(); DataBind(); }