Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to be able to select an option from a drop-down and then display a grid with checkbox option and save the selected options in a database but my code is not working please check.

The goal is to select a subject from the table "subjects" through a dropdown and then display the corresponding CourseOutcomes (which are multiple lines)
in the form of a grid view with checkboxes on the side which then on selection will save the data into another table called savedCLO.


C#
public partial class ModView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=(localdb)\v11.0;Initial Catalog=facultylog;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        {

            String strConnString = ConfigurationManager.ConnectionStrings["facultylogConnectionString"].ConnectionString;
            String strQuery = "select Subject_Name from subjects";
            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strQuery;
            cmd.Connection = con;
            try
            {
                con.Open();
                DropDownList1.DataSource = cmd.ExecuteReader();
                DropDownList1.DataTextField = "Subject_Name";

                DropDownList1.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }
        
        if (!Page.IsPostBack)
        {
            
          refreshdata();
        }

    }

 

    public void refreshdata()
    {
        SqlCommand cmd = new SqlCommand("select CourseOutcomes from CLO", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
   

    
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            var checkbox = gvrow.FindControl("CheckBox1") as CheckBox;
            if (checkbox.Checked)
            {
                var lblId = gvrow.FindControl("Label1") as Label;
                var lblSubjectName = gvrow.FindControl("Label2") as Label;
                var lblCourseOutcomes = gvrow.FindControl("Label3") as Label;


                SqlCommand cmd = new SqlCommand("insert into savedCLO (Id, SubjectName, CourseOutcomes) values (@Id, @SubjectName, @CourseOutcomes)", con);
                cmd.Parameters.AddWithValue("Id", lblId.Text);
                cmd.Parameters.AddWithValue("SubjectName", lblSubjectName.Text);
                cmd.Parameters.AddWithValue("CourseOutcomes", lblCourseOutcomes.Text);
                

                con.Open();
                int i = cmd.ExecuteNonQuery();
                con.Close();
               refreshdata();

            }

        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        String strConnString = ConfigurationManager.ConnectionStrings["facultylogConnectionString"].ConnectionString;
        String strQuery = "select CourseOutcomes from CLO where" + " SubjectName = @Subject_Name";
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();


        cmd.Parameters.AddWithValue("@Subject_Name", DropDownList1.SelectedItem.Value);
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strQuery;
        cmd.Connection = con;
        try
        {
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {

                refreshdata();

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }


ASPX

HTML
    <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" 
="" backcolor="White" bordercolor="#DEDFDE" borderstyle="None" borderwidth="1px" cellpadding="4" forecolor="Black" gridlines="Vertical" style="margin-top: 142px">  
            <alternatingrowstyle backcolor="White">  
            <columns>  
                <asp:templatefield headertext="ID">  
                    <edititemtemplate>  
                        <asp:textbox id="TextBox1" runat="server" text="<%# Bind("Id") %>">  
                      
                    <itemtemplate>  
                    <asp:label id="Label1" runat="server" text="<%# Bind("Id") %>">  

                      

                  

                <asp:templatefield headertext="Subject Name">  
                    <edititemtemplate>  
                        <asp:textbox id="TextBox2" runat="server" text="<%# Bind("SubjectName") %>">  
                      
                    <itemtemplate>  
                        <asp:label id="Label2" runat="server" text="<%# Bind("SubjectName") %>">  
                      
                  

                <asp:templatefield headertext="Course Outcomes">  
                    <edititemtemplate>  
                        <asp:textbox id="TextBox3" runat="server" text="<%# Bind("CourseOutcomes") %>">  
                      
                    <itemtemplate>  
                        <asp:label id="Label3" runat="server" text="<%# Bind("CourseOutcomes") %>">  
                      
                  
                
                <asp:templatefield headertext="Select Applicable">  
                    <edititemtemplate>  
                        <asp:checkbox id="CheckBox1" runat="server">  
                      
                    <itemtemplate>  
                        <asp:checkbox id="CheckBox1" runat="server">  
                      
                  
              
            <footerstyle backcolor="#CCCC99">  
            <headerstyle backcolor="#6B696B" font-bold="True" forecolor="White">  
            <pagerstyle backcolor="#F7F7DE" forecolor="Black" horizontalalign="Right">  
            <rowstyle backcolor="#F7F7DE">  
            <selectedrowstyle backcolor="#CE5D5A" font-bold="True" forecolor="White">  
            <sortedascendingcellstyle backcolor="#FBFBF2">  
            <sortedascendingheaderstyle backcolor="#848384">  
            <sorteddescendingcellstyle backcolor="#EAEAD3">  
            <sorteddescendingheaderstyle backcolor="#575357">  
          
      
        
        <asp:dropdownlist id="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        
        
        
      
          
     
         <asp:button id="Button1" runat="server" onclick="Button1_Click" 
="" text="Save to Database">  


What I have tried:

I have tried the above code but it does not work.
The goal is to select a subject from the table "subjects" through a dropdown and then display the corresponding CourseOutcomes (which are multiple lines)
in the form of a grid view with checkboxes on the side which then on selection will save the data into another table called savedCLO.

Please tell me how to fix this code, I don't want to change the way I'm doing it I just want to fix the current code. I don't want alternative methods because I tried so many and they are all not working out thanks at this point it would be easier to just fix this code. If you do help thanks it means a lot and I'm struggling with this whole project.
Posted
Updated 23-Jun-20 6:07am
v3
Comments
F-ES Sitecore 23-Jun-20 9:15am    
We'd need to see the relevant bits of mark-up in the aspx page and also a definition of what "doesn't work" means.
candijen 23-Jun-20 9:38am    

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False"
="" backcolor="White" bordercolor="#DEDFDE" borderstyle="None" borderwidth="1px" cellpadding="4" forecolor="Black" gridlines="Vertical" style="margin-top: 142px">
<alternatingrowstyle backcolor="White">
<columns>
<asp:templatefield headertext="ID">
<edititemtemplate>
<asp:textbox id="TextBox1" runat="server" text="<%# Bind("Id") %>">

<itemtemplate>
<asp:label id="Label1" runat="server" text="<%# Bind("Id") %>">





<asp:templatefield headertext="Subject Name">
<edititemtemplate>
<asp:textbox id="TextBox2" runat="server" text="<%# Bind("SubjectName") %>">

<itemtemplate>
<asp:label id="Label2" runat="server" text="<%# Bind("SubjectName") %>">



<asp:templatefield headertext="Course Outcomes">
<edititemtemplate>
<asp:textbox id="TextBox3" runat="server" text="<%# Bind("CourseOutcomes") %>">

<itemtemplate>
<asp:label id="Label3" runat="server" text="<%# Bind("CourseOutcomes") %>">



<asp:templatefield headertext="Select Applicable">
<edititemtemplate>
<asp:checkbox id="CheckBox1" runat="server">

<itemtemplate>
<asp:checkbox id="CheckBox1" runat="server">



<footerstyle backcolor="#CCCC99">
<headerstyle backcolor="#6B696B" font-bold="True" forecolor="White">
<pagerstyle backcolor="#F7F7DE" forecolor="Black" horizontalalign="Right">
<rowstyle backcolor="#F7F7DE">
<selectedrowstyle backcolor="#CE5D5A" font-bold="True" forecolor="White">
<sortedascendingcellstyle backcolor="#FBFBF2">
<sortedascendingheaderstyle backcolor="#848384">
<sorteddescendingcellstyle backcolor="#EAEAD3">
<sorteddescendingheaderstyle backcolor="#575357">



<asp:dropdownlist id="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged">






<asp:button id="Button1" runat="server" onclick="Button1_Click"
="" text="Save to Database">




Doesn't work means the grid doesn't show up when I select something from the dropdown

1 solution

There's too much wrong here to bother fixing, I know that's not what you want to hear but you need to get rid of all of this and start from scratch. Break the problem into steps and solve each step fully in turn rather than trying to throw everything at the wall and fixing it all at the same time. You can keep the general method and structure you are using, that's ok, but you need to implement it a step at a time and make sure each step works before moving on, and all that code with issues is complicating that.

Get a drop-down populated from your database (you have two "con" objects BTW, pointing at different databases, and if that is intended it is going to bite you down the road as you'll get confused about which "con" is pointing where)

Give the dropdown an onselectedindexchanged event and an AutoPostback=True attribute. I'm assuming you want that, I don't know for sure. Also make sure the dropdown only binds to your database when !Page.IsPostBack otherwise it will reset to the default state rather than remember what was selected.

On that index changed event get code that reads the relevant data from the database and shows it in a grid. Currently you do a select with a WHERE based on the dropdown but you ignore that data and call refreshdata instead which shows everything. Ignore that function and bind the gridview to the data you get back based on the dropdown, and you shouldn't need to do that in a ".Read()" loop either, just give the gridview the data and it will make one row per result.

You are also binding the gridview to columns that don't exist in the SQL you're getting back (ID and SubjectName), I fail to see how your code can work at all.

Ignore the EditItemTemplate and use only the ItemTemplate, or use both as you are but put the gridview in Edit mode. As it is your gridview is not in edit mode but you're searching for controls that only exist in edit mode ("CheckBox1") so you won't find them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900