locked
How to resolve SQL update RRS feed

  • Question

  • User-218090889 posted

    Hello,

    I have these set of codes as below to do SQL update to a database table, the codes did not give any error message but the table would not update .

    Please can someone have a look at my code to tell me what is wrong

    MY HTML

     <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Enter Your Name </span>
                    <asp:TextBox ID="txtName" runat="server" OnTextChanged="TextBox1_TextChanged" Width="233px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Provide  Name " ForeColor="Red"></asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <span style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666">Enter Your eMail</span>
                    <asp:TextBox ID="txteMail" runat="server" OnTextChanged="txteMail_TextChanged" Width="235px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txteMail" ErrorMessage="Provide eMail" ForeColor="Red"></asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <span style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666">Enter Phone No&nbsp; </span>
                    <asp:TextBox ID="txtPhone" runat="server" OnTextChanged="txtPhone_TextChanged" Width="234px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtPhone" ErrorMessage="Provide Phone No " ForeColor="Red"></asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Enter Country</span>
                    <asp:DropDownList ID="ddlCountry" runat="server" Width="227px" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged" AutoPostBack="True">
                        <asp:ListItem Value="">---select country---</asp:ListItem>
                        <asp:ListItem>Algeria</asp:ListItem>
                        <asp:ListItem>Angola</asp:ListItem>
                        <asp:ListItem>Benin</asp:ListItem>
                        <asp:ListItem>Botswana</asp:ListItem>
                        <asp:ListItem>Burkina</asp:ListItem>
                        <asp:ListItem>Burundi</asp:ListItem>
                        <asp:ListItem>Cameroon</asp:ListItem>
                        
            </asp:DropDownList>
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Gender </span>
            <asp:RadioButton ID="rbtMale" runat="server" Text="Male" GroupName="sex" OnCheckedChanged="rbtMale_CheckedChanged" />
            
            <asp:RadioButton ID="rbtFemale" runat="server" Text="Female" GroupName="sex" OnCheckedChanged="rbtFemale_CheckedChanged" />
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Enter Birty Date </span>
            &nbsp;<asp:TextBox ID="txtBDate" runat="server" OnTextChanged="txtBDate_TextChanged" Width="234px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtBDate" ErrorMessage="Provide Birth Date" ForeColor="Red"></asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Select Security Question&nbsp;</span>
                   <asp:DropDownList ID="ddlSecurityQues" runat="server" Width="227px" OnSelectedIndexChanged="ddlSecurityQues_SelectedIndexChanged" AutoPostBack="True">
                       <asp:ListItem Value="">---Choose a Question---</asp:ListItem>
                       <asp:ListItem>What is the name of your childhood best friend?</asp:ListItem>
                       <asp:ListItem>What is your spouse pet name?</asp:ListItem>
                       <asp:ListItem>What was your high school favorite game?</asp:ListItem>
                       <asp:ListItem>What is your mother's maiden name?</asp:ListItem>
                       <asp:ListItem>In what city did your father wedded your mother?</asp:ListItem>
            </asp:DropDownList>
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Enter Security Answer</span>
                    <asp:TextBox ID="txtSecAnswer" runat="server" OnTextChanged="txtTitle_TextChanged" Width="233px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txtSecAnswer" ErrorMessage="Provide Security Answer" ForeColor="Red"></asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <span  style="font-family: 'Berlin Sans FB'; font-size: small; color: #666666; padding: 2px">Upload Photo</span>
            <asp:FileUpload ID="FileUploadProfile" runat="server" />
                    <br />
                    <br />
                    
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" Width="121px" Height="44px" />
                    <br />
                    
                    <asp:Label ID="lblUploadSuccess" runat="server" style="color: #FF0000; font-size: small; font-weight: 700; font-style: italic; font-family: Arial;"></asp:Label>
                    <br />

    My C# code

    protected void Button1_Click(object sender, EventArgs e)
            {
                if (!object.Equals(Session["UserId"], null))
                {
    
                    if (FileUploadProfile.PostedFile != null)
                    {
                        string userId = Session["UserId"].ToString();
                        string myMap = MapPath("~/").ToLower();
                        Random r = new Random();
                        int next = r.Next();
                        string ImageName = FileUploadProfile.PostedFile.FileName;
                        //ToSaveImageName = DateTime.Now.ToString("yyyy-MM-ddTmm:hh:ss"); //**
                        //ToSaveImageName.Replace('-', '1');                              //**
                        //ToSaveImageName.Replace(':', '2');                              //**
                        //Directory.CreateDirectory(myMap + ToSaveImageName);             //**
                        sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
                        if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
                        {
                            string ImageSaveURL = myMap + "images/" + next + sImageFileExtension;
                            try
                            {
                               
                                FileUploadProfile.PostedFile.SaveAs(ImageSaveURL);
    
    
    
                                string UserIdV = userId;
                                string UserNameV = txtName.Text;
                                string EmailV = txteMail.Text;
                                string PhoneV = txtPhone.Text;
                                string CountryV = ddlCountry.SelectedValue;
                                string GenderV = Request.Form["sex"].ToString();
                                string BirthDateV = txtBDate.Text;
                                string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                string SecurityAnswerV = txtSecAnswer.Text;
                                string PhotoV = next + sImageFileExtension;
                                
    
    
                                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConString"].ToString());
                                SqlCommand cmd = new SqlCommand("UpdateFile", con);
    
                                cmd.CommandType = CommandType.StoredProcedure;
    
                                cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                cmd.Parameters.Add("@BirthDate", SqlDbType.Date).Value = BirthDateV;
                                cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
    
    
                                try
                                {
                                    cmd.Connection = con;
                                    con.Open();
                                    cmd.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    
                                }
                                finally
                                {
    
                                    con.Close();
    
    
                                }
    
    
                            }
                            catch (Exception ex)
                            {
                                
                            }
                            lblUploadSuccess.Text = "File Update Successful";
                            Cleartextbox();
    
    
                        }
                    }

    My Store procedure

    ALTER PROCEDURE [dbo].[UpdateFile]  (
         
    	  @UserId NVARCHAR (128),
    	  @UserName VARCHAR(500),
    	  @Email VARCHAR(500),
    	  @Phone VARCHAR(500),
    	  @Country VARCHAR(500),
    	  @Gender VARCHAR(50),
    	  @BirthDate DATE,      
    	  @SecurityQuestion VARCHAR(2000),
    	  @SecurityAnswer VARCHAR(2000),
    	  @Photo VARCHAR(1000)  
        
    	)  
    AS   
    BEGIN
        SET NOCOUNT ON; 
    	 
        Update [UserProfile] set UserName = @UserName, Email = @Email, Phone = @Phone, Country = @Country, Gender = @Gender, BirthDate = @BirthDate, SecurityQuestion= @SecurityQuestion, SecurityAnswer = @SecurityAnswer, Photo = @Photo  where ID = @UserId;  
          
    END;   
    

    My SQL table

    Column Name Data Type Allow Null
    ID nvarchar(128) No
    UserName varchar(500) No
    Email varchar(500) No
    Phone varchar(500) Yes
    Country varchar(500) Yes
    Gender varchar(50) Yes
    BirthDate date Yes
    SecurityQuestion varchar(2000) Yes
    SecurityAnswer varchar(2000) Yes
    Photo varchar(2000) Yes

    Monday, July 1, 2019 4:00 PM

Answers

  • User-719153870 posted

    yes I still have them, at run time cmd and con are still Null

    According to your description, both con and comm are null, but that sounds abnormal.

    If you can, please be sure to share with us your screenshots of con and comm during debug.

    You can follow the following steps to get detailed information about these two parameters:

    Notice: Make sure that debug has gone through 'SqlCommand CMD = new SqlCommand ("Update File", con); ' (Like in the picture, Yellow bar in 'cmd.CommandType = CommandType.StoredProcedure;') like below:

    Hover your cursor over 'con', you can see the bar in the following image:

    Click on the little triangle icon on the left of bar, you can see the detail information of con:

    And do the same to the cmd:

    We need the last two detailed information screenshots of con and cmd to see what's wrong.

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 10, 2019 4:22 AM

All replies

  • User753101303 posted

    Hi,

    Maybe  a date problem ? (as you pass this value as text, it might fail to convert properly depending on SQL side settings)

    did not give any error message

    By using empty catch blocks, you precisely asked for that. IMHO, never use empty catch blocks. What if you get rid of them ?

    Monday, July 1, 2019 4:52 PM
  • User-218090889 posted

    Maybe  a date problem ? (as you pass this value as text, it might fail to convert properly depending on SQL side settings)

    Please how best can I handle the Date?

    Monday, July 1, 2019 5:14 PM
  • User2053451246 posted

    Did you take the catch blocks out so you can see the error message as the last poster said to do?

    Monday, July 1, 2019 5:18 PM
  • User-218090889 posted

    Did you take the catch blocks out so you can see the error message as the last poster said to do?

    I try modifying it as follows, and what I get is that FileUpload control could not attach file

    this is the modified catch block

     try
                                {
                                    cmd.Connection = con;
                                    con.Open();
                                    cmd.ExecuteNonQuery();
    
    
                                }
                                catch (Exception ex)
                                {
                                    lblUploadSuccess.Text = " File Update fails try again!!!";
                                }
                                finally
                                {
    
                                    con.Close();
                                    Cleartextbox();
    
                                    lblUploadSuccess.Text = "File Update Successful";
                                }
    
                                
                            }
                            catch (Exception ex)
                            {
                                lblUploadSuccess.Text = " File Update fail to attach image!!!";
                            }
    
    

    Monday, July 1, 2019 6:30 PM
  • User753101303 posted

    Please get rid entirely of your catch blocks so that you can see which exception happens. It should be shown in VS or on a real web server, it should be written to the Windows event log.

    Later open maybe a new thread about how to handle exceptions. Currently you are showing the user a message he can't understand (and likely can't solve at all) and throwing away the exception details so that those in charge of running or maintaining the app can't even know that an exception happened.

    Monday, July 1, 2019 6:45 PM
  • User-1204637165 posted

    check the values you are passing into your parameter. Remove the empty catch as they mentioned.

    But check to does values. A wrong date value can cause it. do it carefully you would find the cause of the error.

    Monday, July 1, 2019 10:52 PM
  • User-719153870 posted

    Hi Enzyme,

    Based on the code you provided, I built a demo.

    By debugging several times, i can basically make sure that you have no problem with your database operations and your stored procedures.

    If you've ruled out the date-related reasons, you can infer that your problem is in the save file section.

    The FileUploadProfile.PostedFile.SaveAs() method can’t create new folders at the same time it saves files.

    Your ImageSaveURL is myMap + "images/"+ next + sImageFileExtension, so it cannot find the corresponding path because there is no images folder in your location.

    Please refer to below codes so that you can create a new folder before saving files which will solve your problem:

    protected void Button1_Click(object sender, EventArgs e)
            {
                if (!object.Equals(Session["UserId"], null))
                {
    
                    if (FileUploadProfile.PostedFile != null)
                    {
                        string userId = Session["UserId"].ToString();
                        string myMap = MapPath("~/").ToLower();
                        Random r = new Random();
                        int next = r.Next();
                        string ImageName = FileUploadProfile.PostedFile.FileName;
                        //ToSaveImageName = DateTime.Now.ToString("yyyy-MM-ddTmm:hh:ss"); //**
                        //ToSaveImageName.Replace('-', '1');                              //**
                        //ToSaveImageName.Replace(':', '2');                              //**
                        //Directory.CreateDirectory(myMap + ToSaveImageName);             //**
                        string sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
                        string filename = myMap + "images"; // Add a folder named "images" under myMap
    
                        if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
                        {
                            string ImageSaveURL = myMap + "images\\" + next + sImageFileExtension;
                            try
                            {
                                if (!Directory.Exists(filename)) //If the images folder is not existed, create it
                                {
                                    Directory.CreateDirectory(filename);
                                }
                                FileUploadProfile.PostedFile.SaveAs(ImageSaveURL);
    
                                string UserIdV = userId;
                                string UserNameV = txtName.Text;
                                string EmailV = txteMail.Text;
                                string PhoneV = txtPhone.Text;
                                string CountryV = ddlCountry.SelectedValue;
                                string GenderV = Request.Form["sex"].ToString();
                                string BirthDateV = txtBDate.Text;
                                string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                string SecurityAnswerV = txtSecAnswer.Text;
                                string PhotoV = next + sImageFileExtension;
    
                                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConString"].ToString());
                                SqlCommand cmd = new SqlCommand("UpdateFile", con);
    
                                cmd.CommandType = CommandType.StoredProcedure;
    
    
                                cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                cmd.Parameters.Add("@BirthDate", SqlDbType.Date).Value = BirthDateV;
                                cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
    
                                try
                                {
                                    cmd.Connection = con;
                                    con.Open();
                                    cmd.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
    
                                }
                                finally
                                {
                                    con.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                            lblUploadSuccess.Text = "File Update Successful";
                            Cleartextbox();
                        }
                    }
                }
            }

    Here is result of my demo:

    Best Regard,

    Yang Shen

    Tuesday, July 2, 2019 5:50 AM
  • User-218090889 posted

    If you've ruled out the date-related reasons, you can infer that your problem is in the save file section.

    I can't seem to figure out where the error is, I isolated the Date to test if the issue is the Date, I also modified the save file section as you pointed out, but the update would still not work and no error message.

    Thursday, July 4, 2019 4:32 PM
  • User-719153870 posted

    Hi Enzyme,

    It seems that what we need to do now is to find out what's happening to your project.

    You can try to find the root cause of the problem by doing the following:

    1. If you can, please share all your aspx and cs code. If you don't think it's appropriate, you can also just share the part you've modified.
    2.  You can put break points in front of below codes and denug them to see if they are executed and successful:
      protected void Button1_Click(object sender, EventArgs e)
              {
                  if (!object.Equals(Session["UserId"], null))
                  {
      
                      if (FileUploadProfile.PostedFile != null)
                      {
                          string userId = Session["UserId"].ToString();
                          string myMap = MapPath("~/").ToLower();
                          Random r = new Random();
                          int next = r.Next();
                          string ImageName = FileUploadProfile.PostedFile.FileName;
                          //ToSaveImageName = DateTime.Now.ToString("yyyy-MM-ddTmm:hh:ss"); //**
                          //ToSaveImageName.Replace('-', '1');                              //**
                          //ToSaveImageName.Replace(':', '2');                              //**
                          //Directory.CreateDirectory(myMap + ToSaveImageName);             //**
                          string sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
                          string filename = myMap + "images"; // Add a folder named "images" under myMap
      
                          if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
                          {
                              string ImageSaveURL = myMap + "images\\" + next + sImageFileExtension;
                              try
                              {
                                  if (!Directory.Exists(filename)) //If the images folder is not existed, create it
                                  {
                                      Directory.CreateDirectory(filename);
                                  }
                                  FileUploadProfile.PostedFile.SaveAs(ImageSaveURL);
      
                                  string UserIdV = userId;
                                  string UserNameV = txtName.Text;
                                  string EmailV = txteMail.Text;
                                  string PhoneV = txtPhone.Text;
                                  string CountryV = ddlCountry.SelectedValue;
                                  string GenderV = Request.Form["sex"].ToString();
                                  string BirthDateV = txtBDate.Text;
                                  string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                  string SecurityAnswerV = txtSecAnswer.Text;
                                  string PhotoV = next + sImageFileExtension;
      
                                  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConString"].ToString());
                                  SqlCommand cmd = new SqlCommand("UpdateFile", con);
      
                                  cmd.CommandType = CommandType.StoredProcedure;
      
      
                                  cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                  cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                  cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                  cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                  cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                  cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                  cmd.Parameters.Add("@BirthDate", SqlDbType.Date).Value = BirthDateV;
                                  cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                  cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                  cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
      
                                  try
                                  {
                                      cmd.Connection = con;
                                      con.Open();
                                      cmd.ExecuteNonQuery();
                                  }
                                  catch (Exception ex)
                                  {
      
                                  }
                                  finally
                                  {
                                      con.Close();
                                  }
                              }
                              catch (Exception ex)
                              {
                              }
                              lblUploadSuccess.Text = "File Update Successful";
                              Cleartextbox();
                          }
                      }
                  }
              }

    3.You can try to debug your stored procedures, which you can refer to the link: https://forums.asp.net/t/2156913.aspx

    Best Regard,

    Yang Shen

    Friday, July 5, 2019 1:36 AM
  • User753101303 posted

    And you tried to use the VS debugger to see what happens ? See: 

    https://docs.microsoft.com/en-us/visualstudio/debugger/navigating-through-code-with-the-debugger?view=vs-2019

    Also cmd.ExecuteNonQuery should return what your update statements sends back (ie the number of updated row). If 0 the userId is likely wrong. It is sometimes also that the code just doesn't work agains the database you think etc...

    In short, I often suggest to not just looking at your code and wonder what happens but use debugging tools to see exactly what happens. Sometimes it even happen for example that the event handler is not called at all which is hard to guess by reading but take few seconds to see when using debugging tools.

    Friday, July 5, 2019 11:15 AM
  • User-1126700514 posted

    Hi! You can also try using a BEGIN TRY BEGIN CATCH block in your procedure, and then, make it return a value that lets you know if the error is in the SP or not.

    You can check TRY sintax and doc here:

    https://docs.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-2017

    Regards!

    Friday, July 5, 2019 5:56 PM
  • User-218090889 posted

     You can put break points in front of below codes and denug them to see if they are executed and successful:

    My modified section of the code as below, I tried the various break points suggested, I discovered that the area highlighted yellow in the code below are all showing null,
    I also suspect that the area highlighted green executing.

    protected void Button1_Click(object sender, EventArgs e)
            {
                if (!object.Equals(Session["UserId"], null))
                {
    
                    if (FileUploadProfile.PostedFile != null)
                    {
                        string userId = Session["UserId"].ToString();
                        string myMap = MapPath("~/").ToLower();
                        Random r = new Random();
                        int next = r.Next();
                        string ImageName = FileUploadProfile.PostedFile.FileName;
                        //ToSaveImageName = DateTime.Now.ToString("yyyy-MM-ddTmm:hh:ss"); //**
                        //ToSaveImageName.Replace('-', '1');                              //**
                        //ToSaveImageName.Replace(':', '2');                              //**
                        //Directory.CreateDirectory(myMap + ToSaveImageName);             //**
                        sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
                        string filename = myMap + "images"; // Add a folder named "images" under myMap
    
                        if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
                        {
                            string ImageSaveURL = myMap + "images\\" + next + sImageFileExtension;
    
                            try
                            {
                                if (!Directory.Exists(filename)) //If the images folder is not existed, create it
                                {
                                    Directory.CreateDirectory(filename);
                                }
    
                                FileUploadProfile.PostedFile.SaveAs(ImageSaveURL);
    
                                string UserIdV = userId;
                                string UserNameV = txtName.Text;
                                string EmailV = txteMail.Text;
                                string PhoneV = txtPhone.Text;
                                string CountryV = ddlCountry.SelectedValue;
                                string GenderV = Request.Form["sex"].ToString();
                                string BirthDateV = txtBDate.Text;
                                string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                string SecurityAnswerV = txtSecAnswer.Text;
                                string PhotoV = next + sImageFileExtension;
    
    
                                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());
                                SqlCommand cmd = new SqlCommand("UpdateFile", con);
    
                                cmd.CommandType = CommandType.StoredProcedure;
    
                                cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                cmd.Parameters.Add("@BirthDate", SqlDbType.VarChar).Value = BirthDateV;
                                cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
    
    
                                try
                                {
                                    cmd.Connection = con;
                                    con.Open();
                                    int rows = cmd.ExecuteNonQuery();
    
    
                                }
                                
                                finally
                                {
    
                                    con.Close();
                                    Cleartextbox();
    
                                    lblUploadSuccess.Text = "File Update Successful";
                                }
    
    
                            }
    
    
                            catch (Exception ex)
                        {
                            lblUploadSuccess.Text = " File Update fail to attach image!!!";
                        }
    
    
    
                        }
                        }
                    }
                }

    Saturday, July 6, 2019 10:58 AM
  • User-719153870 posted

    Hi Enzyme,

    It looks like that you can't get the data. Please try put below break points:

    protected void Button1_Click(object sender, EventArgs e)
            {
                if (!object.Equals(Session["UserId"], null))
                {
    
                    if (FileUploadProfile.PostedFile != null)
                    {
                        string userId = Session["UserId"].ToString();
                        string myMap = MapPath("~/").ToLower();
                        Random r = new Random();
                        int next = r.Next();
                        string ImageName = FileUploadProfile.PostedFile.FileName;
                        //ToSaveImageName = DateTime.Now.ToString("yyyy-MM-ddTmm:hh:ss"); //**
                        //ToSaveImageName.Replace('-', '1');                              //**
                        //ToSaveImageName.Replace(':', '2');                              //**
                        //Directory.CreateDirectory(myMap + ToSaveImageName);             //**
                        string sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
                        string filename = myMap + "images"; // Add a folder named "images" under myMap
    
                        if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
                        {
                            string ImageSaveURL = myMap + "images\\" + next + sImageFileExtension;
                            try
                            {
                                if (!Directory.Exists(filename)) //If the images folder is not existed, create it
                                {
                                    Directory.CreateDirectory(filename);
                                }
                                FileUploadProfile.PostedFile.SaveAs(ImageSaveURL);
    
                                string UserIdV = userId;
                                string UserNameV = txtName.Text;
                                string EmailV = txteMail.Text;
                                string PhoneV = txtPhone.Text;
                                string CountryV = ddlCountry.SelectedValue;
                                string GenderV = Request.Form["sex"].ToString();
                                string BirthDateV = txtBDate.Text;
                                string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                string SecurityAnswerV = txtSecAnswer.Text;
                                string PhotoV = next + sImageFileExtension;
    
                                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConString"].ToString());
                                SqlCommand cmd = new SqlCommand("UpdateFile", con);
    
                                cmd.CommandType = CommandType.StoredProcedure;
    
    
                                cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                cmd.Parameters.Add("@BirthDate", SqlDbType.Date).Value = BirthDateV;
                                cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
    
                                try
                                {
                                    cmd.Connection = con;
                                    con.Open();
                                    cmd.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
    
                                }
                                finally
                                {
                                    con.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                            lblUploadSuccess.Text = "File Update Successful";
                            Cleartextbox();
                        }
                    }
                }
            }

    Please make sure if the 'UserNameV = txtName.Text;' gets its value. Like below:

    If you suspect highlighted green executing as you saied, you can see if the 'con' in 'SqlCommand cmd = new SqlCommand("UpdateFile", con);' has value in debugging. Like below:

    Best Regard,

    Yang Shen

    Monday, July 8, 2019 8:22 AM
  • User753101303 posted

    Hi,

    You mean all textboxes are cleared? Could it be that you call  Cleartextbox() from an earlier event such as Page_Load ? I would start by looking at the statement that calls your SP and see the value for "rows". If 0 the update doesn't happen likely because your WHERE clause is wrong.

    BTW using random this way still allow for collision (though maybe unlikely). As it seems an avatar for the user I would likely use the "user id" to save the file.

    Monday, July 8, 2019 8:50 AM
  • User-218090889 posted

    It looks like that you can't get the data. Please try put below break points:

    I tried the break points as you said, the following show that they get data

                                string UserIdV = userId;
                                string UserNameV = txtName.Text;
                                string EmailV = txteMail.Text;
                                string PhoneV = txtPhone.Text;
                                string CountryV = ddlCountry.SelectedValue;
                                string GenderV = Request.Form["sex"].ToString();
                                string BirthDateV = txtBDate.Text;
                                string SecurityQuestionV = ddlSecurityQues.SelectedValue;
                                string SecurityAnswerV = txtSecAnswer.Text;
                                string PhotoV = next + sImageFileExtension;

    but the connection con is null, the ConnectionStrings show count=2

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ToString());
    SqlCommand cmd = new SqlCommand("UpdateFile", con);

    the following are all null

                                cmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserIdV;
                                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserNameV;
                                cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailV;
                                cmd.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneV;
                                cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = CountryV;
                                cmd.Parameters.Add("@Gender", SqlDbType.VarChar).Value = GenderV;
                                cmd.Parameters.Add("@BirthDate", SqlDbType.VarChar).Value = BirthDateV;
                                cmd.Parameters.Add("@SecurityQuestion", SqlDbType.VarChar).Value = SecurityQuestionV;
                                cmd.Parameters.Add("@SecurityAnswer", SqlDbType.VarChar).Value = SecurityAnswerV;
                                cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = PhotoV;
    

    Tuesday, July 9, 2019 3:09 AM
  • User-719153870 posted

    Hi Enzyme,

    By the 'the connection con is null', do you mean the 'ConnectionString' attribute in con is null ?

    If your 'dbConn' can't work normally, you can try to write directly the 'connectionString' string corresponding to 'dbConn' in SqlConnection con = new SqlConnection().

    For example:

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ddd;Integrated Security=true");

    Best Regard,

    Yang Shen

    Tuesday, July 9, 2019 7:58 AM
  • User753101303 posted

    I suspect you are looking at variables before the line that define the value runs. Note that the debugger is highlighting the line that is about to run.

    As it is an update problem and so far it seems there is no runtime error, once again I would look at rows (make sure the debugger is past this line or show this value in a label if your prefer).

    If 0 it means your update statement doesn't select any row (something wrong in the SP or maybe there is no row for the userId in this table).

    Tuesday, July 9, 2019 8:10 AM
  • User-218090889 posted

    Yang Shen

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ddd;Integrated Security=true");

    I tried using connectionstring direct as you suggested, on debugging the cmd.CommandType = CommandType.StoredProcedure; is showing below message

    cmd.CommandType = 'cmd.CommandType' threw an exception of type 'System.NullReferenceException'

    Tuesday, July 9, 2019 11:33 AM
  • User753101303 posted

    You still have the following  ? 

    SqlCommand cmd = new SqlCommand("UpdateFile", con); // Create the cmd object
    cmd.CommandType = CommandType.StoredProcedure; // Use it

    Here it seems cmd is null (do you mean it happens at runtime or do you see that when you try to inspect the value of cmd.CommandType before th cmd=new SqlCommand statement runs ?

    Note that if the debugger is on the cmd=new SqlCommand line, cmd is still null because the debugger points at the line that will run next, not at the one that was just executed....

    Tuesday, July 9, 2019 12:29 PM
  • User-218090889 posted

    You still have the following  ? 

    SqlCommand cmd = new SqlCommand("UpdateFile", con); // Create the cmd object
    cmd.CommandType = CommandType.StoredProcedure; // Use it

    yes I still have them, at run time cmd and con are still Null

    Tuesday, July 9, 2019 2:41 PM
  • User-719153870 posted

    yes I still have them, at run time cmd and con are still Null

    According to your description, both con and comm are null, but that sounds abnormal.

    If you can, please be sure to share with us your screenshots of con and comm during debug.

    You can follow the following steps to get detailed information about these two parameters:

    Notice: Make sure that debug has gone through 'SqlCommand CMD = new SqlCommand ("Update File", con); ' (Like in the picture, Yellow bar in 'cmd.CommandType = CommandType.StoredProcedure;') like below:

    Hover your cursor over 'con', you can see the bar in the following image:

    Click on the little triangle icon on the left of bar, you can see the detail information of con:

    And do the same to the cmd:

    We need the last two detailed information screenshots of con and cmd to see what's wrong.

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 10, 2019 4:22 AM
  • User-218090889 posted

    I have seen where the mistake comes from

    it was the Radio button,

    I changed from Radio Button to RadioButtonList and it worked

    Saturday, July 13, 2019 6:51 AM