2016-05-27 53 views
-1

在這裏,我試圖更新下載計數的一個例如在數據庫中的dwncount列點擊按鈕btndownloadpost。上點擊按鈕它顯示輸入字符串的格式不正確使用命令參數在按鈕

「輸入字符串的不正確的格式」中斷線INT錯誤countid = Convert.ToInt32(e.CommandArgument.ToString());.

db中的countid和dwncount列是int數據類型。 以下是我使用的完整代碼。

按鈕,如下圖所示

<div> 
<asp:Button ID="btndownloadpost" CommandName="download" CommandArgument='<%#Eval("countid") %>' CssClass="btn btn-info" runat="server" Text="Download " OnCommand="btndownloadpost_Command" /> 
</div> 

代碼後面的按鈕

protected void btndownloadpost_Command(object sender, CommandEventArgs e) 
{ 
    if (e.CommandName== "download") 
    { 
     int countid = Convert.ToInt32(e.CommandArgument.ToString()); 
     int i = c.updatedwncount(countid, Convert.ToInt32(ViewState["click"])); 
     if (i > 0) 
     { 

      if (ViewState["click"] != null) 
      { 
       count = (int)ViewState["click"] + 1; 
      } 
      ViewState["click"] = count; 
      Label18.Text = "Updated "; 
     } 


    } 
} 

方法使用

public int updatedwncount(int countid, int dwncount) 
{ 
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString); 
    string sql = "update tbltry set dwncount=dwncount+1 where [email protected]"; 
    SqlCommand cmd = new SqlCommand(sql, con); 
    cmd.Parameters.AddWithValue("@dwncount", dwncount); 
    cmd.Parameters.AddWithValue("@countid", countid); 
    try 
    { 
     con.Open(); 
     return cmd.ExecuteNonQuery(); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
    finally 
    { 
     con.Close(); 
    } 
} 
+0

是按鈕控件是在gridview內嗎? – navnit

回答

0

使用的TryParse代替Convert.ToInt32:

int countid; 
int.TryParse(e.CommandArgument.ToString(), out countid); 

如果Eval表達式暗示輸入無法轉換爲int,則Convert.Int32方法將發出異常。另一方面,TryParse將返回boolean的值,這可以在下一個執行計劃中評估。

參考:Parsing String: Input string was not in a correct format. #

+0

我正在嘗試,但它不工作,可能是我沒有這樣做的寫作方式,所以你可以幫助如何使用它在可能的情況下,因爲代碼給出。您的親切的幫助將值得我很多。謝謝 – sudipchand7139

+0

您能否將Eval語句更改爲像<%#(String.IsNullOrEmpty(Eval(「countid」)。ToString())?0:Eval(「countid」))%>?如果文件沒有下載計數,則這將在零位置處發射零,因此Convert或TryParse方法會將默認值設置爲0。 –

0

我覺得你countid爲空。所以檢查Null值然後解析爲int。

int countid = String.IsNullOrEmpty(e.CommandArgument.ToString()) ? 0 : Convert.ToInt32(e.CommandArgument.ToString());