Inserting All of CheckBoxList Data into DB - asp.net

I have a form that users will fill out and when they submit, all data is pushed to a database.
My Problem is that I have a CheckBoxList and if a user selects multiple checkboxes it only inputs the first item into the database. How do I make it so that all the items are inputted into the same row and separated by commas.
Here is my current code:
protected void Button1_Click(object sender, EventArgs e)
{
//Start Code
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = conString + txtFirst.Text + "','" + txtLast.Text +
"','" + txtEmail.Text + "','" + lstBranch.Text + "','" + lstAccess.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
}

You can loop the items like this
string result = string.Empty;
for (int i = 0; i < checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
result += checkboxlist1.Items[i].Text + ", ";
}
}
// remove the final comma.
// add 'result' to your sql stmt.

Related

How to managed two sql queries in ASP.Net (Visual Studio 2010)

So what I'm trying to do is once I click a button. I want one sql query to insert values to the "Return_Process" Table and another sql query to delete data from the matching loan ID in another table, which is "Loan_Process".
This is the code I have written but its not deleting anything, its inserting the values to the return process but not deleting it from the loan process.
//Global variable declaration
string path;
string sql;
string sql2;
//create a method for database connection
public void connection()
{
//connection string
path = #"Data Source=NATHAN-PC\SQLEXPRESS;Initial Catalog=ASP;Integrated Security=True";
}
protected void Button1_Click(object sender, EventArgs e)
{
{
connection();
SqlConnection con = new SqlConnection(path);
con.Open();
//try
{
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID) VALUES ('" + txtRID.Text + "','" + txtfine.Text + "','" + TextBox1.Text + "','" + txtLID.Text + "')";
sql2 = "Delete FROM Loan_Process WHERE Loan_ID='"+txtLID+"'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
//lblerrormsg.Visible = true;
//lblerrormsg.Text = "Success";
con.Close();
//GridView1.DataBind();
}
//catch (SqlException)
//{
// //lblerrormsg.Visible = true;
// //lblerrormsg.Text = "Invalid";
//}
con.Close();
//GridView1.DataBind();
}
}
}
}
I'm pretty bad at ASP.net, so if someone could tell me what to do to execute both queries at the same time, would greatly appreciate it.
Do something like this:
//your code
sql = "INSERT INTO Return_Process (Return_ID, FIne, Actual_Returned_Date, Loan_ID)"
+ " VALUES (#rid, #fine, #retDate, #lid); " //note ; inside
+ "Delete FROM Loan_Process WHERE Loan_ID=#lid;";
var cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#rid", SqlDbType.Int).Value = Int.Parse(txtRID.Text);
//similar for 3 remaining parameters. Just set correct SqlDbType
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Data is not inserted into database using windows application but not showing any error

Button Click Code
String cs = null;
SqlConnection scon = null;
SqlCommand cmd = null;
private void btnOk_Click(object sender,EventArgs e)
{
String name = txtBoxName.Text.ToString();
String mobile = txtBoxMobile.Text.ToString();
String address = txtBoxAddress.Text.ToString();
String ty = null;
if (radioButtonCow.Checked)
{
ty = radioButtonCow.Text.ToString();
}
else {
ty = radioButtonBuffalo.Text.ToString();
}
int n = 0;
using(scon = new SqlConnection(cs)){
scon.Open();
String query = "insert into new_customer(name,mobile,address,type)
values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
cmd = new SqlCommand(query, scon);
n = cmd.ExecuteNonQuery();
}
}
private void NewCustomer_Load(object sender, EventArgs e)
{
cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
}
}
When I run this application it runs successfully without showing any error but it doesn't insert any records in the table. The table has the fields id, name, mobile, address and type. id is a primary key and it's an identity field. All the other fields are of varchar type.
Why doesn't it insert data in the table?
You just pass your parameters in this way as i mentioned below,
SqlConnection scon = new SqlConnection(cs);
scon.Open();
String query = "insert into new_customer values(#name,#mobile,#address,#type)";
cmd = new SqlCommand(query, scon);
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#name",mobile);
cmd.Parameters.AddWithValue("#name",address);
cmd.Parameters.AddWithValue("#name",ty);
cmd.ExecuteNonQuery();
scon.Close();
try by wrap the type field as [type]
String query = "insert into new_customer(name,mobile,address,[type]) values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";

Why isn't my database logic throwing an exception when I enter data that already exists?

I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}

how to insert value to sql db from dynamically generated textboxes asp.net

First of all im really new to Visual Studio and Asp.net C# and so on...
I'm creating a simple rental application for bicycles and just got stuck.
I made a Formula for adding a order for one bike and made an insert into at a submit buttonclick without Problem.
Now to my Problem..
It is possible for the same customer to rent more bikes at the same time and instead of filling out the Formula again for every new bike i want to be able to add more bikes to the same Formula (1 bike = Serial Number)
To do this I found a solution on the web where i took away the Serial Number field and made a field where the user fills in the amount of bikes the customer wants to rent and then a button next to the field. When the user then writes for example 3 in the amount field and presses the button it automatically Pop ups 3 textboxes for Input of every bikes Serial Number.
Now i Need some solution for inserting the value of this textboxes with the Serial numbers..
After pressing the button that makes the insert to my SQL db i have to make some Loop to Count how many inserts i have to make and also print in the different values of the Serial numbers for the each order.
example:
1 customer 3 bikes
bike 1 = Serial Number 123
bike 2 = Serial Number 234
bike 3 = Serial Number 345
now i have to make 3 insert into with this 3 different Serial numbers after clicking the send order button.
Am i on the right track?
protected void btnGenerateControl_Click(object sender, EventArgs e)
{
int Count = Convert.ToInt32(Qty.Text);
for(int i =1; i <= Count; i++)
{
TextBox txtbox = new TextBox();
txtbox.Text = "Textbox - " + i.ToString();
pnlTextBoxes.Controls.Add(txtbox);
}
}
protected void btnAddOrder_Click(object sender, EventArgs e)
{
int Count = Convert.ToInt32(Qty.Text);
for (int i = 1; i <= Count; i++)
{
String query = "insert into Orders (CustID, OrderDate, Time, ProductID, ProjectID, Status, FlottenID)values('" + CustID.Text + "','" + OrderDate.Text + "','" + Time.Text + "','" + ProductID.Value + "','" + ProjectID.Value + "','" + Status.Value +"','" +HERE I NEED TO CATCH THE VALUE OF SERIAL NUMBER+ "')";
String query1 = "commit;";
DataLayer.DataConnector dat = new DataLayer.DataConnector("Provider=SQLOLEDB; data source=****;database=event;user ID=****;password=*****; Persist Security Info=False");
dat.DataInsert(query);
dat.DataInsert(query1);
}
}
Write the below code in btnGenerateControl_Click1 Event(below For Loop)
pnlTextBoxes.Controls.Add(new LiteralControl("<input id='txt' name='Textbox" + i + "'type='text' />"));
pnlTextBoxes.Controls.Add(new LiteralControl("<br />"));
And Write the below code in the btnAddOrder_Click1 event(below For Loop)
String query = "insert into Orders (CustID, OrderDate, Time, ProductID, ProjectID, Status, FlottenID)values('" + CustID.Text + "','" + OrderDate.Text + "','" + Time.Text + "','" + ProductID.Value + "','" + ProjectID.Value + "','" + Status.Value + "','" + Request.Form["Textbox" + i.ToString()] + "')";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.ExecuteNonQuery();
Hai I got Output By Using Temperory data(Not like your data).So by Using the Below Logic You can get your output.
At First I take database table like
orders(id int,person_name varchar(20))
Then according to my database I use the logic below.Here I use label for checking only
public partial class stack_over : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
string connString = "Your Database Connection String";
protected void btnGenerateControl_Click1(object sender, EventArgs e)
{
int Count = Convert.ToInt32(Qty.Text);
for (int i = 1; i <= Count; i++)
{
pnlTextBoxes.Controls.Add(new LiteralControl("<input id='txt' name='Textbox" + i + "' type='text' />"));
pnlTextBoxes.Controls.Add(new LiteralControl("<br />"));
}
}
protected void btnAddOrder_Click1(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(connString);
con.Open();
int Count = Convert.ToInt32(Qty.Text);
for (int i = 1; i <= Count; i++)
{
Label1.Text = Request.Form["Textbox"+i.ToString()];
String query = "insert into Orders values('" + Label1.Text + "','ajay')";
MySqlCommand cmd = new MySqlCommand(query,con);
cmd.ExecuteNonQuery();
}
}
}
Hope You can get Idea from this Code.
Happy Programming......

Accessing Textbox from GridView data cell (ASP.NET)

protected void GridView2_OnCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Reply")
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + selectedRow.Cells[2].Text + div + DateTime.Now.ToString() + div + selectedRow.Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(FindControl(selectedRow.Cells[1].UniqueID))).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
Any ideas how to implement this?
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Reply")
{
on = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + GridView2.Rows[index].Cells[2].Text + div + DateTime.Now.ToString() + div + GridView2.Rows[index].Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(GridView2.Rows[index]Cells[1].FindControl("the name of the text box")).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
catch (Exception ee)
{
string message = ee.Message;
}
}
Note:1- in aspx :CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
2- use RowCommand event for the grid view.

Resources