validating dynamically created radio buttons using Response.write

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • satyabhaskar
    New Member
    • Dec 2008
    • 32

    validating dynamically created radio buttons using Response.write

    hi all,
    In my web page i have created radio buttons dynamically on to the page .....following is my code
    Code:
             string Course, Semester, Section;
        int rowsCount;
        string con = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SqlConnection objCon;
                SqlDataAdapter objDA;
                Course = (string)Session["Course"];
                Semester = (string)Session["Semester"];
                Section = (string)Session["Section"];
                if (!IsPostBack)
                {
                    string strFeedBackDetails = "";
                    Response.Write("<i>COURSE</i>  <b>  :" + Course + " </b>  |   ");
                    Response.Write("<i>SEMESTER</i> <b>   :" + Semester + "</b>   |   ");
                    Response.Write("<i>SECTION </i><b>  :" + Section + "</b><br/><br/><br/><br/>");
                    string query = "select SubjectCode from tblCollegeSubject where CourseName = '" + Course + "' and Semester = '" + Semester + "' union select miscSubject from tblCollegeMisc";
                    objCon = new SqlConnection(con);
                    objDA = new SqlDataAdapter(query, objCon);
                    DataTable objDT = new DataTable("tblSubjectCode");
                    objDA.Fill(objDT);
                    rowsCount = objDT.Rows.Count;
                    strFeedBackDetails += "<div align=\"center\"><table align=\"center\" cellpadding=\"5\" cellspacing=\"2\" frame=\"border\" bordercolordark=\"#000000\">" +
                       "<tr  bgcolor=Gray><th><b>SUBJECT</b></th>" +
                       "<th><b>EXCELLENT-1</b></th><th><b>VERY GOOD-2</b></th>" +
                       "<th><b>GOOD-3</b></th><th><b>AVERAGE-4</b></th>" +
                       "<th><b>POOR-5</b></th><th><b>COMMENTS</b></th></tr>";
    
                    for (int count = 0; count < rowsCount; count++)
                    {
                        strFeedBackDetails += "<tr><td style=\"font-style: italic;\"><input type=text name=\"subject\" readonly=\"readonly\" id=\"txtSubject" + count.ToString() + "\" value='" + objDT.Rows[count]["SubjectCode"].ToString() + "' style=\"display: block; visibility: visible;\"></td>";
                        strFeedBackDetails += "<td><input type=radio id='rbgrade1" + count.ToString() + "' value=\"A\" name='grade" + count.ToString() + "' /></td>";
                        strFeedBackDetails += "<td><input type=radio id='rbgrade2" + count.ToString() + "' value=\"B\" name='grade" + count.ToString() + "' /></td>";
                        strFeedBackDetails += "<td><input type=radio id='rbgrade3" + count.ToString() + "' value=\"C\" name='grade" + count.ToString() + "' /></td>";
                        strFeedBackDetails += "<td><input type=radio id='rbgrade4" + count.ToString() + "' value=\"D\" name='grade" + count.ToString() + "' /></td>";
                        strFeedBackDetails += "<td><input type=radio id='rbgrade5" + count.ToString() + "' value=\"E\" name='grade" + count.ToString() + "' /></td>";
                        strFeedBackDetails += "<td><input type=text id='txtComments" + count.ToString() + "' name=\"txtComments\" maxlength=200 /> </td>";
                        strFeedBackDetails += "</tr>";
                    }
                    strFeedBackDetails += "<tr><td colspan=7 align=center><input type=\"submit\" id=\"btnSave\" value=\"Save\" language=\"javascript\" onClick=\"return Save()\"  /></td>";
                    strFeedBackDetails += "<td><input type=hidden id=\"hidCount\" name=\"hidCount\" value='" + objDT.Rows.Count.ToString() + "'/></td></tr>";
                    strFeedBackDetails += "</table></div>";
                    Page.Form.Controls.Add(new LiteralControl(strFeedBackDetails));
                }
                else
                {
                    string lstrSubject = null;
                    string lstrComments = null;
                    string[] larrSubject = null;
                    string[] larrComments = null;
                    int lrowsCount = Convert.ToInt16(Request["hidCount"]);
                    lstrSubject += (Request["subject"]);
                    lstrComments += (Request["txtComments"]);
                    larrSubject = lstrSubject.Split(',');
                    //showControlids();                       
                    larrComments = lstrComments.Split(',');
                    string[] lgrade = new string[lrowsCount];
                    objCon = new SqlConnection(con);
                    SqlCommand objCmd = new SqlCommand("uspInsFeedBack", objCon);
                    objCmd.CommandType = CommandType.StoredProcedure;
                    objCmd.Parameters.Add("@FeedBackDate", SqlDbType.DateTime).Value = System.DateTime.Now.ToString();
                    objCmd.Parameters.Add("@CourseName", SqlDbType.Char).Value = Course;
                    objCmd.Parameters.Add("@Semester", SqlDbType.Char).Value = Semester;
                    objCmd.Parameters.Add("@SectionName", SqlDbType.Char).Value = Section;
                    SqlParameter RetVal = objCmd.Parameters.Add("@Refer", SqlDbType.Int);
                    RetVal.Direction = ParameterDirection.Output;
                    try
                    {
                        objCon.Open();
                        objCmd.ExecuteNonQuery();
                        for (int count = 0; count < lrowsCount; count++)
                        {
                            lgrade[count] = (Request["grade" + count.ToString()]);                        
                            string insertSQL;
                            insertSQL = "INSERT INTO tblCollegeFeedBackForm(";
                            insertSQL += "SubjectCode, FeedBackId, Grade, Comments)";
                            insertSQL += "VALUES (";
                            insertSQL += "@SubjectCode, @FeedBackId, @Grade, @Comments )";
                            SqlCommand objCmd1 = new SqlCommand(insertSQL, objCon);
                            objCmd1.Parameters.Add(new SqlParameter("@SubjectCode", SqlDbType.Char));
                            objCmd1.Parameters["@SubjectCode"].Value = larrSubject[count];
                            objCmd1.Parameters.Add(new SqlParameter("@FeedBackId", SqlDbType.Int));
                            objCmd1.Parameters["@FeedBackId"].Value = RetVal.Value;
                            objCmd1.Parameters.Add(new SqlParameter("@Grade", SqlDbType.Char));
                            objCmd1.Parameters["@Grade"].Value = lgrade[count];
                            objCmd1.Parameters.Add(new SqlParameter("@Comments", SqlDbType.VarChar, 200));
                            objCmd1.Parameters["@Comments"].Value = larrComments[count];
                            objCmd1.ExecuteNonQuery();                      
                        }
                    }
                    catch (SqlException er)
                    {
                        Response.Write(er.Message);
                    }
                    finally
                    {
                        objCon.Close();
                    }
                }
            }
            catch (Exception er)
            {
                Response.Write(er.Message);
            }
        }
    And now i want to validate the page before it get submited...i want the user to check radio buttons in each row.. i validated using javascript as follows
    Code:
    <script language="javascript" type="text/javascript">
    <!--
    
    function Save() 
    {
        var countId=getElementByName('hidCount');
        var Count=countId.value;
        var check='check';
        for(i=0;i<count;i++)
        {
            var grade[i]=getElementByName('grade'+i);
            for(j=0;j<grade[j].length;i++)
            {
                if(grade[j].checked==true)
                {
                    check=grade[i].value();
                }
             }
             if(check=='check')
             {
                alert('PLZ Grade The Subject');
                return false;
             }           
             else
                return true;
         }
    }
    i cold not able to validate becoz i could not get the the value of hidden variable and radio button....can any one plz solve by problem...


    thanks
    Last edited by tlhintoq; Feb 27 '09, 03:19 PM. Reason: [CODE] not <code> but thanks for trying to tag
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    The first thing I'm going to say is that Response.Write should not be used in your C# code.

    Why would I say such a thing?

    Glad you asked, it writes the content "somewhere" in the output content stream.

    What on earth does that mean?

    Well it means that when you use Response.Write( ), the string is written anywhere in the content stream sent to the browser. This usually results in the content being placed somewhere before the <html> tag, or somewhere between the <head> and <body> tags....

    If you don't believe me, run your application, right click on it and click "view code"...

    Do you see it?

    Your HTML isn't valid is it?

    Response.Write should only be called from the asp code.
    Not used in the C# code.

    This is probably why you're having problems.

    I strongly recommend you use ASP.NET controls since you are developing an ASP.NET application.

    In your case, I would recommend looking up the RadioButtonList Control, Repeaters .....and Labels

    Comment

    • bhupinder
      New Member
      • Feb 2009
      • 32

      #3
      Hi satyabhaskar,

      frinvale sir is right you can use response.write.

      Code:
            Page.Form.Controls.Add(new LiteralControl(strFeedBackDetails));
      insted this code you can write this way
      Code:
      Response.Write(strFeedBackDetails);
      but if you want to check validation you have to make function in javascript;
      whenever you find control in javascript you use this line

      Code:
      document.getElementByName 
      //(or)
      document.getElemenetById
      Last edited by Frinavale; Mar 2 '09, 02:06 PM. Reason: Added [code] tags: Please place code in [code][/code] tags

      Comment

      • satyabhaskar
        New Member
        • Dec 2008
        • 32

        #4
        Originally posted by Frinavale
        The first thing I'm going to say is that Response.Write should not be used in your C# code.

        Why would I say such a thing?

        Glad you asked, it writes the content "somewhere" in the output content stream.

        What on earth does that mean?

        Well it means that when you use Response.Write( ), the string is written anywhere in the content stream sent to the browser. This usually results in the content being placed somewhere before the <html> tag, or somewhere between the <head> and <body> tags....

        If you don't believe me, run your application, right click on it and click "view code"...

        Do you see it?

        Your HTML isn't valid is it?

        Response.Write should only be called from the asp code.
        Not used in the C# code.

        This is probably why you're having problems.

        I strongly recommend you use ASP.NET controls since you are developing an ASP.NET application.

        In your case, I would recommend looking up the RadioButtonList Control, Repeaters .....and Labels
        hi boss...
        yes boss ur right.... im sorry the title which i displayed is wrong. actually i did not used response.write. .. i find the same fault which u said and i changed my code accordingly.... i used
        Code:
         Page.Form.Controls.Add(new LiteralControl(strFeedBackDetails));

        and nw my problem is i couldnt get the control's id when iam validating them client side using java script......... i don't need to validate all the controls its enough if i can validate radio buttons in each row....

        Comment

        • satyabhaskar
          New Member
          • Dec 2008
          • 32

          #5
          hey boss i got the solution.... just want to share..... my code is as follows...
          Code:
          <script language="javascript" type="text/javascript">
          function valid(e)
          {
              for(var i=0;i<e.length;i++)
              {
                  if(e[i].type=='radio')
                  {
                      var r=e[e[i].name], check=true;
                      for(var j=0;j<r.length;j++)
                      {
                          if(r[j].checked)
                              check=false;
                      }
                      if(check)
                      {
                          alert('Please Grade All The Subjects');
                          return false;
                      }
                      else
                       return true;
                  }
              }
          }
          </script>
          </head>
          <body>
              <form id="form1" method="post" name="form1" runat="server" onsubmit="return valid(this.elements)" >
              </form>
          </body>
          </html>

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            I'm glad you found your solution :)

            For your information, the reason why you couldn't get the control's ID for validation using JavaScript is because Literal Controls just print pure text. This text does not have an ID associated with it...

            If you had used a Label, your text would have been rendered in <span> tags, which has an ID that will let you access it with JavaScript.

            In your case, you want to validate a RadioButtonList , which has an ID...

            Your solution works fine for your purposes though: loop through all of the elements in the page and find a Radio Button List....then validate.

            For more information check out how to use JavaScript in ASP.NET

            Comment

            Working...