2013-03-28 23 views
-2

我有,它產生下面的下拉列表默認值:.NET下拉列表中與C#

與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]"; 
    } 

之所以我有,如果是因爲我們如果用戶選擇:選擇網站,我不想做SELECT,因爲沒有siteId值選擇網站。

有沒有更有效的方法來做到這一點?

回答

3

首先,我推薦閱讀關於Sql Injections,你應該真正參數化你的查詢。第二,既然你有DataText和DataValue屬性,你可以讓「SelectSite」爲Text屬性,並且Value爲0或-1(或者只是空的)。兩個網站

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

無需和 SITEID

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的更多信息:

無論哪種方式,你可以做這樣的事情。