1

我要做的是将用户名及其每月小时限制插入我的 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();
}
4

2 回答 2

5

您需要配置数据源以使用参数。

 <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" />
于 2013-03-15T15:21:40.650 回答
0
Datasource.InsertCommand is a property.
Datasource.Insert() is a method.

您还应该使用参数。

datasource.insertparameters("username").defaultvalue = TextBox1.Text + "," + TextBox2.Text
于 2013-03-15T15:17:28.990 回答