您的位置:首页 > 数据库

绑定SqlDataSource实现增删改查(FormView为例)

2014-05-12 14:50 169 查看
页面拖入SqlDataSource,点击右上角三角号进行数据源配置,指定需要的数据库后选择指定的表和列,此时会自动生成查询SQL语句。再点击旁边的高级按钮,勾选生成INSERT、UPDATE、DELETE语句。VS会自动生成相应的SQL语句和参数。点击确定按钮完成DATASOURCE的配置。

拖入的FORMVIEW控件选择数据源为刚才已配置的SQLDATASOURCE。现在FORMVIEW控件已经可以完成增删改查功能。

如果要为FormView设定一个可以查询上一条和下一条记录的功能,需要改变VS自动生成的SelectCommand语句,加上WHERE查询条件并加上参数

<SelectParameters>

               <asp:Parameter Name="ParameterName" Type="String" />

 </SelectParameters>

在上下条数据按钮的点击事件中加上

 SqlDataSource1.SelectParameters["ParameterName_id"].DefaultValue = "";//设定每次点击上下条数据按钮时WHERE查询条件的参数值。

此外,VS自动生成的ItemTemplate等各部门都可以自行修改。

比如将模板中的Course栏从自带的Textbox转为DropDownList

可以在EditItemTemplate和InsertItemTemplate中将原来的Course改为

 <asp:DropDownList ID="DDL" runat="server" Width="153px">

                                <asp:ListItem></asp:ListItem>

                                <asp:ListItem>计算机</asp:ListItem>

                                <asp:ListItem>英语</asp:ListItem>

                               <asp:ListItem>语文</asp:ListItem>

 </asp:DropDownList>

同时写上INSERT和UPDATE事件按钮 <asp:Button ID="UpdateButton" runat="server" CausesValidation="True" Text=" 保 存 " OnClick="UpdateButton_Click"></asp:Button>

<asp:Button ID="InsertButton" runat="server" CausesValidation="True" Text=" 保 存 " OnClick="InsertButton_Click"></asp:Button>

在后台为Course参数赋值:

 protected void UpdateButton_Click(object sender, EventArgs e)

    {       

        SqlDataSource1.UpdateParameters["course"].DefaultValue = ((DropDownList)this.FormView1.FindControl("DDL")).SelectedValue;

        this.FormView1.UpdateItem(true);

    }

    protected void InsertButton_Click(object sender, EventArgs e)

    {     

        SqlDataSource1.InsertParameters["course"].DefaultValue = ((DropDownList)this.FormView1.FindControl("DDL2")).SelectedValue;

        this.FormView1.InsertItem(false);

    }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp