我想做的是将用户名及其每月的小时限制插入到我的 SQL Server 数据库中。我使用自动生成的语句进行更新和删除。我现在只需要添加新用户。据我所知,下面的代码应该可以工作,但事实并非如此。我想这就是我写的方式。
注释中的部分是 Userdata.aspx
文件自动生成的内容,因此我试图将其转换为使用我的 2 个文本框。
非常感谢。
protected void Button1_Click1(object sender, EventArgs e)
{
string sql = "INSERT INTO [UserData]([UserName], [MonthlyHourLimit]) VALUES ("+ TextBox1.Text + "," + TextBox2.Text + ")";
//INSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (@UserName, @MonthlyHourLimit)"
SqlDataSource1.InsertCommand = sql;
GridView1.DataBind();
}
最佳答案
您需要配置数据源以使用参数。
<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
SelectCommand="select [UserName], [MonthlyHourLimit] from [UserData] where UserName= @UserName"
InsertCommand="IINSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (@UserName, @MonthlyHourLimit);"
ConnectionString="<%$ ConnectionStrings:MyConnection %>"
RunAt="server">
<SelectParameters>
<asp:Parameter Name="UserName" Type="Int32" DefaultValue="0" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="UserName" Direction="Input" Type="String" />
<asp:Parameter Name="MonthlyHourLimit" Direction="Input" Type="String" />
</InsertParameters>
</asp:sqlDataSource>
更新:我忘了说,您想使用 ControlParameter而不是简单的参数。看看下面的片段:
<asp:СontrolParameter Name="UserName" ControlId="ddlUserNames" PropertyName="SelectedValue"/>
...
<asp:DropdownList
ID="ddlUserNames"
runat="server"
Autopostback="True">
<asp:Listitem Selected="True">Users</asp:Listitem>
<asp:Listitem Value="Peter">Peter</asp:Listitem>
<asp:Listitem Value="Jessica">Jessica</asp:Listitem>
</asp:Dropdownlist>
看看对应的MSDN页面详细描述了 SqlDataSource 的用法。
更新 2:完整示例以避免混淆
<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"
SelectCommand="select [UserName], [MonthlyHourLimit] from [UserData] where UserName= @UserName"
InsertCommand="IINSERT INTO [UserData] ([UserName], [MonthlyHourLimit]) VALUES (@UserName, @MonthlyHourLimit);"
ConnectionString="<%$ ConnectionStrings:MyConnection %>"
RunAt="server">
<SelectParameters>
<asp:Parameter Name="UserName" Type="Int32" DefaultValue="0" />
</SelectParameters>
<InsertParameters>
<asp:ControlParameter Name="UserName" ControlId="txtUserName" Direction="Input" Type="String" />
<asp:ControlParameter Name="MonthlyHourLimit" ControlId="txtMonthlyHourLimit" Direction="Input" Type="String" />
</InsertParameters>
</asp:sqlDataSource>
<asp:TextBox runat="server" ID="txtUserName" />
<asp:TextBox runat="server" ID="txtMonthlyHourLimit" />
关于c# - 插入 SQL Server 数据库 ASP.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435859/