带有c#的默认值的.NET下拉列表

时间:2013-03-28 17:01:26

标签: c# asp.net

我有一个下拉列表,其中包含以下内容:

具有SiteId的可能值:

 "Select Site"
 "1"
 "2"
 "3"
 "4"

请注意,选择网站是默认值:

    <asp:DropDownList ID="ddlSite" DataSourceID = "siteDS" runat="server" OnSelectedIndexChanged="ddlSite_SelectedIndexChanged" AutoPostBack="true" DataTextField="SiteName" 
            DataValueField="SiteId" AppendDataBoundItems="true">
            <asp:ListItem>Select Site</asp:ListItem>
    </asp:DropDownList>

我有以下查询,但不确定是否有更好的方法

     // this checks to see if the value is Select Site or an actual siteid (1,2,3)
     int siteID = 0;
     int Site;
     bool result = Int32.TryParse(ddlSite.SelectedValue, out Site);
     if (result)
     {
        siteID = Site;
     }


     if (result)
     {
        NTDS.SelectCommand = "SELECT *  FROM [tbl1] where siteId = " + siteID;
     }
     else
     {
        NTDS.SelectCommand = "SELECT *  FROM [tbl1]";
     }

我有if else的原因是因为我们如果用户选择:选择Site,我不想做SELECT,因为没有siteId值为Select Site。

有更有效的方法吗?

2 个答案:

答案 0 :(得分:3)

首先,我建议阅读Sql Injections,你应该真正参数化你的查询。

其次,既然你有DataText和DataValue属性,你可以让“SelectSite”成为Text属性,让Value为0或-1(或者只是空)。

无论哪种方式,你都可以这样做:

if (Int32.TryParse(ddlSite.SelectedValue, out Site) && Site  > 0)
{
    // Parameterized SELECT
}
else
{
  ...
}

不需要Site SiteId

答案 1 :(得分:1)

// your initial item or better off you can add a client side validator
// preventing them from submitting the page with the initial value, also call Page.IsValid on server side to make sure they didn't hacked your client side validation.
if (ddlSite.SelectedIndex != 0)
{
   var siteId = 0;
   if (int.TryParse(ddlSite.SelectedValue, out siteId)
   {
      // then here build a helper for adding conditions if siteId is present.
      // try using parameterized queries for avoiding sql injection.
   }
   else
   {
      // call your same helper without siteId and it should be smart enough to
      // return a query without where clause.
   }
}

有关parameterized queries的更多信息。