Insert multiple dynamic text box data into database - c#

My goal is to... Click on a button and it creates some text boxes. User types in the info and if there is more info (in this case different houses they might be interested in ) to put in. They keep clicking the add button and more boxes appear. When they are done they click insert and all of the data inserts.
Right now what I have is a user can click it once and insert data and it works. What I am having trouble with is having a way to keep the ID counted in a way where I don't have to type in "txtDynamic1", "txtDyamic2", etc..
Also, the parameter #name can only be used once. So I don't understand if the only way to do this would be to click insert and then it wipes the data from the text box and they can retype for more.
I am not sure if my envision is possible where they could click however many adds for text boxes and then insert it all with one button click. I have a gridview for this set up but it does it one at a time as well... Any help would be so much appreciated as I have sunk way too many hours into this.
Sorry if this isn't explained clearly enough as my brain is fried at this point.
public partial class Sold : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = 1;
for (j = 1; j < 3; j++)
{
int index = pnl.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
pnl.Controls.Add(txt);
// Literal lt = new Literal();
// lt.Text = "<br />";
// pnl.Controls.Add(lt);
}
protected void Button2_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TI_Homes(CustomerID, Year, Make, Size, Owed, Offer, Wholesale) VALUES('1000', #name, #year, '80ft', '100,000', '80,000', 'Wholesale?')"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", (pnl.FindControl("txtDynamic1") as TextBox).Text);
cmd.Parameters.AddWithValue("#year", (pnl.FindControl("txtDynamic2") as TextBox).Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}

Although I advise against trying to do this on the server side, what you need to do is keep their state on postback meaning you will have to store them in something like session or viewstate (boo) restore them on postback and then loop over the form controls in your button click. Then you will have access to the #name parameter line by line in the loop (only needing it once). Below is the idea but I haven't used web forms in years so you'll need to check the syntax.
protected void Button2_Click(object sender, EventArgs e)
{
foreach(var control in Page.Controls)
{
if(control is TextBox)
{
if(((TextBox)control).ID.IndexOf("txtDynamic") != -1)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TI_Homes(CustomerID, Year, Make, Size, Owed, Offer, Wholesale) VALUES('1000', #name, #year, '80ft', '100,000', '80,000', 'Wholesale?')"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", ((TextBox)control).Text);
cmd.Parameters.AddWithValue("#year", (pnl.FindControl("txtDynamic2") as TextBox).Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
}

Related

Cannot insert item from dropdown menu into my database

I am new to C# and i am trying to insert some values to my database i created inside visual studio.
-I am creating a recipe application-
So in the form i have some components such as text boxes(For title,ingredients,description), a dropdown item(combobox) to specify if it's food or sweet and a button to insert all these data into my database.
When i am pressing the button i can add everything(all the text boxes) to the database except the dropdown value.
Here is the code inside the button_click
private void addItemButton_Click(object sender, EventArgs e)
{
string dat = "Insert into [Table](Title,Category,Ingredients,Description) Values('" + titleTextBox.Text + "','" + dropdownCategory.SelectedValue + "','" + addIngredientTextBox.Text + "','" + addDescriptionTextBox.Text + "')";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
I make a code example, which can insert the combobox value to the database successfully.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string dat = string.Format("Insert into [Sample](Title,Category,Ingredients,Description)values('{0}','{1}','{2}','{3}')", textBox1.Text, comboBox1.SelectedItem,textBox2.Text,textBox3.Text);
string connectionString = #"connectionstring";
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(dat, sqlCon);
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("success");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.AddRange(new object[] { "basketball","football", "volleyball" });
}
}
I would try to look into content of string dat.
It might contain invalid data if "dropdownCategory.SelectedValue" returns something
that you don't expect.
Other than that, order of Open(), ExecuteNonQuery() and Close() methods might be incorrect. Try to read docs of these methods.
Another thing that you should look into is error message that is returned(if there is one). They are usually pretty informative.
Ok i don't know if it's correct or not but it worked on me.
I changed
dropdownCategory.SelectedValue
to
dropdownCategory.Text
and it worked.

textBoxName.Text isn't getting the text entered by user, only the text that was set there on load

I have this textbox:
<asp:TextBox ID="txtDescription" runat="server" Height="90%" TextMode="MultiLine" Width="90%"></asp:TextBox>
and I set its' text value:
description = reader["Description"].ToString();
txtDescription.Text = description;
This is for editing the "description" so I have the existing description in the box and then want to get the text that is in the box at the end as it has been altered.
However I do:
string newDecription = txtDescription.Text;
and the value is that which it was initially set as. The above code to get the text value is ran on a submit button, so isn't somehow running and getting the value before it has been edited.
CONTEXT
protected void Page_Load(object sender, EventArgs e)
{
getValues();
}
string ID = 1;
protected void getValues()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand("SELECT Name,Stock,Price250g,Price1kg,Description,StockOrdered FROM Stock WHERE id = #ID", conn))
{
comm.Parameters.AddWithValue("#ID", ID);
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
price250g = reader["Price250g"].ToString();
price1kg = reader["Price1kg"].ToString();
name = reader["Name"].ToString();
description = reader["Description"].ToString();
stock = reader["Stock"].ToString();
stockOrdered = Convert.ToBoolean(reader["StockOrdered"].ToString());
lblName.Text = name;
lbl250g.Text += price250g.Remove(price250g.Length - 2);
lbl1kg.Text += price1kg.Remove(price1kg.Length - 2);
lblStock.Text = stock + "g";
cbStockOrdered.Checked = stockOrdered;
txtDescription.Text = description;
}
}
}
}
private void addAddressToOrder()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Stock SET Name=#name, Stock=#stock, Price250g=#price250, Price1kg=#price1kg, Description=#description, StockOrdered=#ordered WHERE Id=#ID", conn))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#description", txtDescription.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#price250", txtPrice250g.Text);
cmd.Parameters.AddWithValue("#price1kg", txtPrice1kg.Text);
stock = ddAddStock.SelectedValue + stock;
cmd.Parameters.AddWithValue("#stock", stock);
cmd.Parameters.AddWithValue("#ordered", cbStockOrdered.Checked);
conn.Open();
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
addAddressToOrder();
Response.Redirect("~/Admin/AdminHome.aspx");
}
This commonly happens when you do this:
protected void Page_Load(object sender, EventArgs e)
{
// other code
txtDescription.Text = description;
}
The reason is because of the page lifecycle events. Page_Load executes every time the page is loaded. This includes post-backs. (After all, you need to load the page in order to interact with it.) And it runs before any button handlers or other similar control events. So if this code, which writes a value to the text box, is executing before you read a value from the text box then it's going to overwrite that value.
Any code in Page_Load (or similar page initialization events) which shouldn't run on post-backs needs to be wrapped in a conditional:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// other code
txtDescription.Text = description;
}
}

Find a specific record in Access and display the records into textboxes

Hey Im new to stacoverflow and would like to ask some help. I need to type a ID into a textbox and when searched is clicked it will find the record and display each of the colum values to text boxes. Im using a access database. I have found solution on this but they dont seem to work. I have found and ajusted the following code but give an error op conn.open() and is coded in C#. Please help me.
source Code:
public partial class FamilyTree : UserControl
{
private OleDbConnection conn;
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void ConnectToDatabase()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb");
conn.Open();
}
private void DisconnectDatabase()
{
conn.Close();
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
string queryString = "SELECT * FROM FamilyTree" + txtID ;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = conn;
conn.Open();
OleDbDataReader dr = command.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
conn.Close();
}
Ensure that the 'ConnectToDatabase()' method is called somewhere before using 'conn' in btnSearch_Click.
Next, decide whether you are using the Id or Title to filter the result.
When creating the queryString, ensure you use the 'WHERE Id = ' or 'WHERE Title = ' clause to filter - but also ensure that you have a space between the end of the queryString and the value added at the end - the example you have given would produce 'SELECT * FROM FamilyTree23' if the Id was 23. This would error because there is no table with this name in the database.
Finally, as mentioned in other answers, 'using' a database connection, and using query parameters are a better practice. The 'using' statement will release the connection automatically after use, and a parameterised query prevent will SQL Injection issues and ensure correct data types are passed to the query.
Example:
public partial class FamilyTree : UserControl
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hannes\Documents\Visual Studio 2013\Projects\fam\fam\Prog.mdb";
public FamilyTree()
{
InitializeComponent();
}
private void FamilyTree_Load(object sender, System.EventArgs e)
{
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
string title = txtID.Text.ToString();
sqlQuery = "SELECT * FROM FamilyTree WHERE Title = ?";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("Title", title);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
txtSex.Text += dr["gendre"].ToString();
txtColour.Text += dr["name"].ToString();
txtDOB.Text += dr["DOB"].ToString();
txtStatus.Text += dr["city"].ToString();
txtCock.Text += dr["mom"].ToString();
txtHen.Text += dr["dad"].ToString();
}
}
}
}
}

one button click creates two events

I need to create a button that makes two events and saves it into database (arrival and departure time of employee).
What i need to do First click on button saves arrival time of employee to database, Second click on same button saves departure time of employee (instead of having 2 buttons ofcourse)
I think i need some kind of counter that counts button clicks, or something like that, but i really have no clue how to program sth like that, so if you could please help me out.
This is what i have so far Please notice that the code does not work, so there is no problem except for me not knowing how to program it. Thank you
int counter = 0;
public void button1_Click(object sender, EventArgs e)
{
counter++;
try
{
if (counter == 1)
{
OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "Insert into Weekdays (Arrival)" + "values(#Arrival)";
cmd.Parameters.AddWithValue("#Arrival", DateTime.Now);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Arrival added.");
myConnection.Close();
}
else if (counter == 2)
{
OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "Insert into Weekdays (Departure)" + "values(#Departure)";
cmd.Parameters.AddWithValue("#Departure", DateTime.Now);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Departure added.");
myConnection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You could create a bool to indicate whether the employee is clocked in yet or not.
bool clockedIn = false;
public void button1_Click(object sender, EventArgs e)
{
if (!clockedIn)
{
// employee just arrived - log arrival time
}
else
{
// employee leaving - log departure time
}
clockedIn = !clockedIn;
}
Quick and dirty way:
private void button1_Click(object sender, EventArgs e)
{
if (button1.Tag == null)
{
button1.Tag = "toogled";
// run event 1
}
else
{
button1.Tag = null;
// run event 2
}
}

How to use SqlCommand and DataAdapter in order to manipulate SQL Server with C#

I create table called Department with 2 columns Department ID which is auto increment and Department Name
I create Navigate_Department() in order to walk through the department rows
System.Data.SqlClient.SqlConnection con;
DataSet Dep_ds;
System.Data.SqlClient.SqlDataAdapter Dep_da;
int Dep_MaxRows = 0;
int Dep_inc = 0;
private void ILS_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ILS_DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
Dep_ds = new DataSet();
string sql2 = "select * from Department order by DepartmentID";
Dep_da = new System.Data.SqlClient.SqlDataAdapter(sql2, con);
Dep_da.Fill(Dep_ds, "Department");
Navigate_Department();
Dep_MaxRows = Dep_ds.Tables["Department"].Rows.Count;
}
private void Navigate_Department()
{
DataRow dRow = Dep_ds.Tables["Department"].Rows[Dep_inc];
Dep_ID.Text =dRow.ItemArray.GetValue(0).ToString();
Dep_Name.Text = dRow.ItemArray.GetValue(1).ToString();
}
private void Move_Next_Click(object sender, EventArgs e)
{
if (Dep_inc != Dep_MaxRows-1)
{
Dep_inc++;
Navigate_Department();
}
else
{
MessageBox.Show("No More Records");
}
}
private void Move_back_Click(object sender, EventArgs e)
{
if (Dep_inc > 0)
{
Dep_inc--;
Navigate_Department();
}
else
{
MessageBox.Show("First Record");
}
}
private void Dep_Clear_Click(object sender, EventArgs e)
{
Dep_ID.Clear();
Dep_Name.Clear();
}
private void Dep_Add_Click(object sender, EventArgs e)
{
try
{
SqlCommand insCmd = new SqlCommand("insert into dbo.Department (DepartmentName) values ('" + Dep_Name.Text + "')", con);
Dep_da.InsertCommand = insCmd;
Dep_MaxRows = Dep_MaxRows + 1;
Dep_inc = Dep_MaxRows - 1;
Dep_Max.Text = Dep_MaxRows.ToString();
Dep_Current.Text = (Dep_MaxRows).ToString();
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.Message);
}
The problem is:
After I click clear button, I insert the department name into Dep_Name textbox then click add button. The name that I inserted didn’t get saved in the database, and if I click move back then move next in order to see what I inserted, I get a Index out of range exception in the Navigate_Department() method.
So did I make any mistake?
The reason the name you're inserting isn't saved in the database is because you never execute the insert command. Add:
int ret = Dep_da.Update(Dep_ds);
after the
Dep_da.InsertCommand = insCmd;
The variable ret will contain the number of rows successfully updated (inserted) - which in your case should be 1.
To add to what #N. Warfield wrote, if you simply append raw data into your SQL string that a user (or another system, for that matter) provides, you leave yourself wide-open to SQL injection attacks.
Rather than create the insert statement like this you should use the data adapter with an insert command, add a new DataRow instance to the table then use the data adapter to execute the update.
Alternatively you could execute the insert command within Dep_Add_Click by replacing the call to "Dep_da.InsertCommand = insCmd" with "insCmd.ExecuteNonQuery", however this would mean that you would need to re-run the select statement and repopulate the dataset from the database to get the data from the database into the dataset.

Categories

Resources