Hi KatieNgoc,
Refer below sample.
Place your checkboxes in side a panel. Then looping through the controls of type checkbox get the chcked checkbox value as comma separated string.
After getting the value as comma separated you can insert it in database.
HTML
CS.aspx
<asp:Panel runat="server" ID="pnlCheckBoxBind">
<asp:CheckBox ID="CheckBox1" runat="server" Text="Jobtitle1" />
<br />
<asp:CheckBox ID="CheckBox2" runat="server" Text="Jobtitle2" />
<br />
<asp:CheckBox ID="CheckBox4" runat="server" Text="Jobtitle3" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Jobtitle4" />
<br />
<asp:CheckBox ID="CheckBox5" runat="server" Text="Jobtitle5" />
</asp:Panel>
<br />
<asp:Button Text="Insert" runat="server" OnClick="Save" />
Default.aspx
<asp:GridView ID="gvCheckedValues" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Message" HeaderText="Message" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
CS.aspx.cs
protected void Save(object sender, EventArgs e)
{
string message = "";
foreach (CheckBox checkBox in pnlCheckBoxBind.Controls.OfType<CheckBox>())
{
if (checkBox.Checked)
{
message += checkBox.Text + ",";
}
}
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("INSERT INTO tblCheckValue VALUES(@Message)", con);
cmd.Parameters.AddWithValue("@Message", message.Trim(','));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd = new SqlCommand("SELECT Message FROM tblCheckValue", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Session["dt"] = dt;
Response.Redirect("Default.aspx");
}
DefaultCS.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = Session["dt"] as DataTable;
gvCheckedValues.DataSource = dt;
gvCheckedValues.DataBind();
}
VB.Net
VB.aspx.vb
Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
Dim message As String = ""
For Each checkBox As CheckBox In pnlCheckBoxBind.Controls.OfType(Of CheckBox)()
If checkBox.Checked Then
message += checkBox.Text & ","
End If
Next
ScriptManager.RegisterStartupScript(Me, Me.GetType(), " ", "alert('" & message.Trim(","c) & "');", True)
End Sub
DefaultVB.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handle Me.Load
Dim dt As DataTable = TryCast(Session("dt"), DataTable)
gvCheckedValues.DataSource = dt
gvCheckedValues.DataBind()
End Sub
Screenshot