Passing DropDownList SelectedValue to SQL Query th

2019-08-31 03:44发布

I'm working on an ASP.NET webforms page that queries the database for a list of entries in the Study table. These entries are to be passed into the dropdownlist. When a study is selected from the dropdownlist, the studyID is to be passed to the GetResponses method to retrieve associated data from a stored procedure.

I receive Input String was not in a Correct Format with the following snippets:

 private DataTable LoadStudies(int iStudyID )
{
    ddlStudies.Items.Clear();
    ddlStudies.SelectedValue = "0";

    DataTable dt = new DataTable();
    using (PROTOTYPING db = new PROTOTYPING(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString))
    {
        var query = (from d in db.Studies
            where d.StudyStatus == 0 //Closed...
            orderby d.StudyName
            select new
            {
                d.StudyName,
                d.StudyID,
            });
        if (query.Count() > 0)
        {
            foreach (var a in query)
            {
                ddlStudies.Items.Add(new ListItem(a.StudyID.ToString()));
            }
        }

        dt.Dispose();
        DataView dv = new DataView(dt);
        return dt;
    }
}

The error is thrown on the Page_Load which is currently written as follows:

protected void Page_Load(object sender, EventArgs e)
{
    int iUserID = 0;

    if (Session["UserID"] == null)
    {
        Response.Redirect("Default.aspx");
    }
    iUserID = Convert.ToInt32(Session["UserID"]);
    int iRole = 0;
    iRole = Convert.ToInt32(Session["RoleID"]);

    if (!Page.IsPostBack)
    {

        LoadStudies(Convert.ToInt32(ddlStudies.SelectedValue));
        GetResponses(Convert.ToInt32(ddlStudies.SelectedValue));

        ddlStudies.DataSource = LoadStudies(Convert.ToInt32(ddlStudies.SelectedValue));
        ddlStudies.DataTextField = "StudyName";
        ddlStudies.DataValueField = "StudyID";
        ddlStudies.DataBind();
    }
}

How do I resolve the error, which is thrown when assigning the dropdownlist's DataSource to the LoadStudies method?

1条回答
Melony?
2楼-- · 2019-08-31 04:30

ddlStudies.SelectedValue is not a valid integer value 0,1,2 etc.

I would wager a guess it's an empty string. Convert.ToInt32(""), which will throw the exception you are experiencing.

Interestingly Convert.ToInt32(null) will return a zero.

Try Convert.ToInt32(string.IsNullOrWhiteSpace(ddlStudies.SelectedValue) ? null : ddlStudies.SelectedValue)

查看更多
登录 后发表回答