DropDownList索引问题

时间:2013-12-13 20:12:47

标签: c# drop-down-menu

我正在尝试从存储过程数据库连接绑定DropDownList。我能够使用表的唯一标识字段和“Unit_ID”字段填充dropDownList。 DropDownList上正确填充了信息。但是,当从列表中选择所选项并将值存储到存储过程插入时,我收到索引超出范围错误。这是我的代码:

private void DisplayUnitType()
{

  SqlConnection Db_Connection = new SqlConnection(Utilities.PageUtils.ConStr);
  SqlDataAdapter DA = new SqlDataAdapter("SM_GET_UNITS", Db_Connection);
  DA.SelectCommand.CommandType = CommandType.StoredProcedure;
  DataSet DS = new DataSet();
  DA.Fill(DS, "Units");
  this.DropDownList_Unit_Type.DataSource = DS.Tables["Units"].DefaultView;
  this.DropDownList_Unit_Type.DataTextField = "Unit_Name";
  this.DropDownList_Unit_Type.DataValueField = "Unit_ID";
  this.DropDownList_Unit_Type.DataBind();
  //
}

protected void Button_Submit_Click1(object sender, ImageClickEventArgs e)
{
  RegisterUser();
}
private void RegisterUser()
{
  string UnitAdministratorInfo = string.Empty;
  try
    {

      SqlConnection conn = new SqlConnection(Utilities.PageUtils.ConStr);
      // format Validation code
      string code = Utilities.PageUtils.MD5encrypt(System.DateTime.Now.ToString() + Session["User_Id"].ToString());
      // define data reader7
      SqlCommand cmdInsertUser = new SqlCommand("RG_INSERT_NEW_USER2",conn);
      cmdInsertUser.CommandType = CommandType.StoredProcedure;

      cmdInsertUser.Parameters.AddWithValue("@Unit_Id", this.DropDownList_Unit_Type.SelectedItem.Value); //Trying to insert unique item value from dropdown to here
      cmdInsertUser.Parameters.AddWithValue("@Validation_Code",code);
      cmdInsertUser.Parameters.AddWithValue("@User_Id",Session["User_Id"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@First_Name",Session["First_Name"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Last_Name",Session["Last_Name"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Password",Utilities.PageUtils.MD5encrypt(Session["Password"].ToString()));
      cmdInsertUser.Parameters.AddWithValue("@Middle_Name",Session["Middle_Name"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Email_Address",Session["Email_Address"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Color_Id",1);
      cmdInsertUser.Parameters.AddWithValue("@DSN",Session["DSN"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Phone",Session["Phone"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Zip_Code",Session["Zip_Code"].ToString());
      cmdInsertUser.Parameters.AddWithValue("@Organization",Session["Organization"].ToString());
      conn.Open();
      cmdInsertUser.ExecuteNonQuery();
      cmdInsertUser.Parameters.Clear();
      conn.Close();
    }
  catch(SqlException ex)
    {
      ErrorHandler.Catcher.CatchToDb(ex, "Register2.aspx", Request, Utilities.PageUtils.ConStr);
      Response.Write(Session["User_Id"].ToString() + "<br>" + "</ br>");
      Response.Write(ex.ToString());
      if(ex.ToString().IndexOf("duplicate") != -1 || ex.InnerException.ToString().IndexOf("duplicate") != -1)
        {
          if(Session["User_Id"] == null || Session["User_Id"].ToString() == "") Response.Redirect(Utilities.PageUtils.ErrorPage+"?Error_Message=An error occurred while processing your registration.  Please try again.  If the problem persists, please notify a system administrator.", false);
          else
            {
              Session["User_Id"] = Session["User_Id"].ToString() + "1";
              RegisterUser();
              return;
            }
        }
    }
  try
    {

这是我的错误:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error: 


Line 126:           catch(SqlException ex)
Line 127:           {
Line 128:               ErrorHandler.Catcher.CatchToDb(ex, "Register2.aspx", Request, Utilities.PageUtils.ConStr);
Line 129:               Response.Write(Session["User_Id"].ToString() + "<br>" + "</ br>");
Line 130:               Response.Write(ex.ToString());


Source File: g:\Documents\Visual Studio 2010\WebSites\myWebSite\Register2.aspx.cs    Line: 128 

Stack Trace: 


[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
   System.Collections.ArrayList.get_Item(Int32 index) +7493656
   System.Collections.Specialized.NameObjectCollectionBase.BaseGetKey(Int32 index) +13
   System.Collections.Specialized.KeysCollection.Get(Int32 index) +11
   System.Collections.Specialized.KeysCollection.get_Item(Int32 index) +7
   ErrorHandler.Catcher.CatchToDb(Exception ex, String User_Id, HttpRequest Req, String ConStr) +1670
   Register2.RegisterUser() in g:\Documents\Visual Studio 2010\WebSites\NacWebSite\Register2.aspx.cs:128
   Register2.Button_Submit_Click1(Object sender, ImageClickEventArgs e) in g:\Documents\Visual Studio 2010\WebSites\myWebSite\Register2.aspx.cs:93
   System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +108
   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +118
   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3649; ASP.NET Version:2.0.50727.3648 

1 个答案:

答案 0 :(得分:0)

看起来Session [[User_ID“]没有值,而在catch块中你试图用

引用它

Response.Write(Session["User_Id"].ToString()....

您可以尝试以下方式:

string user_ID = Session["User_Id"] != null? Session["User_Id"].ToString(): "No value for Session[User_Id]"

Response.Write(user_ID + "...")