0

I have problem when I was trying to insert values of generate-able checkbox into a SQL Server database using ASP.NET and C#.

The problem happens when I want to take the checkbox ID because the ID can be unlimited. I had run this code below, but whenever I clicked submit button, it just refreshing the page.

Here is my ASP.NET markup:

<div class="panel-body">
    <div class="col-lg-1">
        <div id="kolom_a">
            <input type="checkbox" id="q1" runat="server" class="form-control"/>
            <input type="checkbox" runat="server" id="q2" class="form-control"/>
            <input type="checkbox" runat="server" id="q3" class="form-control"/>
        </div>
    </div>

    <div class="col-lg-11">
        <div id="kolom_b">
            <input type="text" class="form-control"  runat="server" id="a1"/>
            <input type="text" runat="server" class="form-control" id="a2"/>
            <input type="text" runat="server" class="form-control" id="a3"/>
        </div>
    </div>

    <input type="hidden" id="qty" value="3"/>

    <div class="row">
        <div class="col-lg-12" style="padding-top:15px;">
          <div class="col-lg-4"></div>
          <div class="col-lg-2">
              <input type="reset" onclick="kolom_a()" class="btn btn-default btn-block btn-group-lg" value="Tambah">
          </div>
          <div class="col-lg-2">
              <input type="button" onclick="hapus_a()" class="btn btn-default btn-block btn-group-lg" value="Hapus">
          </div>
          <div class="col-lg-4"></div>
      </div>
</div>

<script>
    function kolom_a() {
        var qty = document.getElementById('qty').value;
        var new_qty = parseInt(qty, 10) + 1;
        if (new_qty < 3) {
            new_qty = 3;
        }
        document.getElementById('qty').value = new_qty;

        var x = document.createElement("INPUT");
        x.setAttribute("type", "checkbox");
        x.setAttribute("name", "type");
        x.setAttribute("class", "form-control");
        x.setAttribute("id", 'q' + new_qty);
        x.setAttribute("runat", "server");
        document.getElementById("kolom_a").appendChild(x);

        var x = document.createElement("INPUT");
        x.setAttribute("type", "text");
        x.setAttribute("class", "form-control");
        x.setAttribute("id", 'a' + new_qty);
        x.setAttribute("runat", "server");
        document.getElementById("kolom_b").appendChild(x);
    }

    function hapus_a() {
        var qty = document.getElementById('qty').value;
        var new_qty = parseInt(qty, 10) - 1;

        if (new_qty < 3) {
            new_qty = 3;
        }

        document.getElementById('qty').value = new_qty;

        var hapus = document.getElementById("kolom_a");
        hapus.removeChild(hapus.childNodes[new_qty]);

        var hapus = document.getElementById("kolom_b");
        hapus.removeChild(hapus.childNodes[new_qty]);
    }
    </script>
</div>
<asp:Button ID="simpan" runat="server" class="btn btn-primary btn-block btn-group-lg" text="Simpan" OnClick="simpan_Click"/>

Here is my code behind:

private string koneksi = WebConfigurationManager.ConnectionStrings["Databaseku"].ConnectionString;

protected void simpan_Click(object sender, EventArgs e)
{
    int qty = Convert.ToInt32(qty = 0);
    string base64Guid = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

    for (int i = 0; i < qty; i++)
    {
        string jawaban = string.Empty;

        string SQL = "INSERT INTO question (id_question, type, title, category, feedback, points, columns) VALUES ('" + base64Guid + "','Benar Salah','" + judul.Text + "','" + kategori.Value + "', '" + umpan.Text + "', '" + poin.Text + "', '" + qty + "')";
        string SQL2 = "INSERT INTO question_type_match (id_questionmatch, question, answer) VALUES ('" + base64Guid + "','q' '" + i + "','a' '" + i + "')";

        SqlConnection conn = new SqlConnection(koneksi);

        SqlCommand comm = new SqlCommand(SQL, conn);
        SqlCommand comm2 = new SqlCommand(SQL2, conn);

        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
            comm2.ExecuteNonQuery();
            Response.Redirect("../daftarpertanyaan.aspx");
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            conn.Close();
        }
    }
}
1
  • SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection Commented Jan 11, 2017 at 17:05

1 Answer 1

1

Your qty variable is always 0 as per

int qty = Convert.ToInt32(qty = 0);

therfore loop never executes

***** EDIT based on author's comment below.

If you want to access the value of the field in the code behind, it has to be an ASP.NET control, same as your button. Therefore your hidden field should be declared as follows:

<asp:HiddenField ID="qty" Value="3" runat="server" />

if you do that, you will be able to access its value in the code behind:

var quantity = int.Parse(qty.Value);

and your loop should be:

for (int i = 0; i < quantity; i++)

I'm sure your next question will be about JS not being able to access the field. You will notice that in the HTML generated the ID of that input will be something like: MainContent_qty. To be able to select that input by javascript you can add a class to your field:

<asp:HiddenField ID="qty" Value="3" runat="server" class="qty_selection" />

and use the javascript class selector:

var qty = document.getElementsByClassName('qty_selection')[0].value;

***** EDIT 2:

You cannot simply "generate" controls names like that. Do a basic c# tutorial and then try reading some tutorials on web forms (if you want to use them over MVC) showing how to save to database. The current way is VERY unsafe due to SQL injection. Sorry, but looking at your last example code I'd have to teach you the basics of programming which is far away from your question. You can refer to:

https://www.microsoft.com/net/tutorials/csharp/getting-started

https://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/introduction-and-overview .

Sign up to request clarification or add additional context in comments.

3 Comments

So, what should I do? the value of qty should be take from <input type="hidden" id="qty" value="3"/>
Thanks, I have the other problem. How to insert the checkbox checked value into database? I tried using ` string check = string.Empty; if ('q'+i.Checked) { check = "Y"; } else { check = "N"; } ` But there was an error on 'q'+i.Checked. It said 'int' does not contain a definition for 'checked'
Thanks, I know it's unsafe due to SQL injection. I will learn then fix it later because I need to done this project soon. Anyway, is it forbidden to generate form-control when we want to insert its value into database?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.