Somthing wrong with the logic, it's not insert its data to server and its not display after second visit. Do I need session? Do you have any ideas?
Default.aspx
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
Name :
<asp:TextBox runat="server" ID="txtName" />
<br />
Security Question
<br />
Your favourite Fruites :
<asp:CheckBox ID="CheckBox1" Text="Orange" runat="server" />
<asp:CheckBox ID="CheckBox2" Text="Apple" runat="server" />
<asp:CheckBox ID="CheckBox3" Text="Grapes" runat="server" />
<br />
<asp:Button Text="Login" runat="server" OnClick="Insert" />
</div>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace displayCheckbox
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["Citistaff"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name,Fruites FROM tblDatas", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
string fruites = dt.Rows[i][1].ToString();
foreach (var control in this.Controls)
{
if (control is CheckBox)
{
string text = (control as CheckBox).Text;
if (fruites.Contains(text))
{
(control as CheckBox).Checked = true;
}
}
}
}
}
}
}
}
}
protected void Insert(object sender, EventArgs e)
{
string message = "";
string constr = ConfigurationManager.ConnectionStrings["Citistaff"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblDatas(Name,Fruites) VALUES(@Name,@Fruites)", con))
{
foreach (var control in this.Controls) // I guess this is your form
{
if (control is CheckBox)
{
if (((CheckBox)control).Checked)
{
message = ((CheckBox)control).Text;
}
}
}
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@Fruites", message);
con.Open();
int i = Convert.ToInt16(cmd.ExecuteNonQuery());
con.Close();
if (i > 0)
{
Response.Redirect("About.aspx");
}
}
}
}
}
}
About.aspx
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace displayCheckbox
{
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
}