Submit Dynamically generated inputs to SQL - c#

I have a Java Script dynamically creating rows in a table when a contact is added. Each contact added I want to submit them to a cell in a sql database. I have no issues submitting the first contact but i need to use a loop (maybe a for loop?) to submit all of the contacts added to the dynamically created rows in the table. I am very new to the C# community and looking for a little help on how to do this.
When the rows are created via Java Script I also have it creating an input with a 'name' value, this name value is what is used to submit to the cell in the database.
Thanks in advance
Code is below:
JavaScript
function flNames() {
var rowID = parseInt(document.getElementById("ContactsRowCount").value, 10);
rowID++;
if (currentRow > 0) {
saveEdits();
} else {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var sHtml = "<tr id='row" + rowID + "'>" +
"<td class='tblStyle68wlb' id=\"FirstN" + rowID + "\">" + firstName + "</td><input type=\"hidden\" value=\"" + firstName + "\" name=\"cFirst\" />" +
"<td class='tblStyle68wl' id=\"LastN" + rowID + "\">" + lastName + "</td><input type=\"hidden\" value=\"" + lastName + "\" name=\"cLast\" />" +
"<td class='tblStyle68wl' ><button type='button' class='XsmallButtons' onclick='editRow(" + rowID + ")'>Edit</button></td>" +
"<td class='tblStyle68wlb' ><button type='button' class='XsmallButtons' onclick='deleteRow(" + rowID + ")'>Delete</button></td>" +
"</tr>";
$("#dynamicTableTesting").append(sHtml);
newRow++;
document.getElementById("ContactsRowCount").value = rowID;
$("#firstName, #lastName").val("");
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
GetFormData();
}
private void GetFormData()
{
string dynamicFirstName = Request.Form["cFirst"];
string dynamicLastName = Request.Form["cLast"];
string tableContactID = Request.Form[""];
string sql = #"
INSERT INTO
tableContactData
(
fName
,lName
)
VALUES
(
#cFirst
,#cLast
);
SELECT SCOPE_IDENTITY();
";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("cFirst", dynamicFirstName);
cmd.Parameters.AddWithValue("cLast", dynamicLastName);
conn.Open();
tableContactID = cmd.ExecuteScalar().ToString();
conn.Close();
}

Related

Inserting Multiple selected Listbox items into the same cell in SQL table

I want to insert multiple list box items into a a cell In SQL table with a comma dividing the items. The code posted below will only add the first selected item within a listbox. Hence If you select 2 or 10 items the first one u selected will be Inserted into the table. The for loop is my problem, I need to get all the selected values.
Thanks
protected void pg_upload_Click(object sender, EventArgs e)
{
using (SqlConnection mycon = new SqlConnection(connectionstring))
{
using (SqlCommand mycmd = mycon.CreateCommand())
{
if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
}
else
{
string str = "";
for (int i=0; i<= listbox_software.Items.Count; i++)
{
str = listbox_software.SelectedItem.ToString();
}
mycon.Open();
mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
"Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' , '" + str + "')";
mycmd.ExecuteNonQuery();
PopulateGridView();
lblsuscessmessage.Text = "Selected Record Added";
lblerrormessage.Text = "";
textbox_make.Text = string.Empty;
textbox_number.Text = string.Empty;
textbox_asset.Text = string.Empty;
textbox_ip.Text = string.Empty;
textbox_serial.Text = string.Empty;
textbox_os.Text = string.Empty;
textbox_memory.Text = string.Empty;
}
}
}
}
Add following namespace:
using System.Linq;
Create a string array of selected items and then use string.join:
var selection = listbox_software.SelectedItems
.Cast<string>()
.ToArray();
var str = string.Join(",", selection);
I found out the answer.
// To access checkbox list item's value //
string total = "";
foreach (ListItem listItem in listbox_software.Items)
{
if (listItem.Selected)
{
total = total + "[" + listItem.Value + "][ " + " ";
}
}
string str = total.ToString();

How to get a single string variable from SqlDataAdapter code

I have this nifty code that takes selected data from a sql table and adds it to an email body. It will (thanks to the help of stack overflow geniuses) return multiple records and group them in the email body very nicely. Problem is - the email field. of course, it is in the For each loop and returns multiple instances of that record - which, in turn, writes to the To field in email. This record is always the same and I only want one instance written to my variable (eml). I'm guessing this would be simple - but I am not coming up with a good solution short of performing the query again.
string str = #"Data Source=srvr;Initial Catalog=db;Integrated
Security=True";
SqlConnection scn;
SqlDataAdapter da;
DataSet ds;
salesOrdersTableAdapter.SO(_TST_TWIDataSet.SalesOrders);
scn = new SqlConnection(str);
da = new SqlDataAdapter("SELECT DISTINCT DATEADD (dd, DATEDIFF(dd,0,ShipDate),0) AS ShipDate,RTRIM(SalesOrder) AS [Sales Order], RTRIM(PartNum) AS [Part Number]," +
"RTRIM(Description) AS Description,RTRIM(DueQty) AS Quantity,RTRIM(CustPartNum) AS[Customer Part No], RTRIM(CustPo) AS[Customer PO], " +
"RTRIM(CustRev) AS[Customer Rev], RTRIM(email) AS [Email] " +
"FROM tbl WHERE Ack <> 'Y'AND SalesOrder =" + MyGlobals.ord, scn);
ds = new DataSet();da.Fill(ds, "SalesOrders");
var orderListBody = new StringBuilder();
var sbj = string.Empty;
foreach (DataRow Row in ds.Tables["SalesOrders"].Rows)
{
orderListBody.Append("Order Number " + Row["Sales Order"] + "<br />");
orderListBody.Append("Part Number: " + Row["Part Number"] + "<br />");
orderListBody.Append("Description: " + Row["Description"] + "<br />");
orderListBody.Append("Customer Part Number: " + Row["Customer Part No"] + "<br />");
orderListBody.Append("Customer Revision: " + Row["Customer Rev"] + "<br />");
DateTime dte = DateTime.Now;
orderListBody.Append("Expected Ship Date: " + dte.ToShortDateString() + "<br />");
orderListBody.Append("Quantity: " + Row["Quantity"] + "<br />");
orderListBody.Append("<br />");
// eml += Row["Email"];
sbj = "Order Acknowledgement for your PO " + Row["Customer PO"];
}
thanks in advance
Just call ToString() on the object returned by the row indexer:
eml = Row["Email"].ToString();

How to insert multiple data into database?

i would like to insert multiple data into my database. I am using for-each statement to get the data and when i insert into the database, it generates 10(just a random no. depending on the no. of data i retrieved) rows for me with one data in every row instead of all in one row. here is the for-each statement i am using.
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + kiev.Key + " ) VALUES ( '" + kiev.Value + "' ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();
}
}
There are better options like "SqlBulkCopy" available as already mentioned in the comments but also something like this should work:
string tablename = "";
string values = "";
string keys = "";
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
keys += kiev.Key + ", ";
values += "'" + kiev.Value + "', ";
}
}
keys = keys.Remove(keys.Length - 2);
values = values.Remove(values.Length - 2);
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + keys + " ) VALUES ( " + values + " ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();

Devexpress c# how to insert MultiSelectedItems(checkboxrowselect) from grid to Database

I have gridview which is bound to the dataset and trying to insert multipleselectedrows(CheckBoxRowSelect) to my database but everytime I failed. I tried many different ways but there is no result. My codes are for insert:
int[] selectedrows = gridView1.GetSelectedRows();
for (int i = 0; i < selectedrows.Length; i++)
{
string sql = "INSERT INTO dbo.TABLE1(COL1,COL2,COL3) SELECT " + gridView1.GetRowCellValue(i, "COL4") + "," + gridView1.GetRowCellValue(i, "COL5") + ",'" + gridView1.GetRowCellValue(i, "COL6")" FROM dbo.TABLE2 WHERE COL4=" + gridView1.GetRowCellValue(i, "COL4") + " AND COL5=" + gridView1.GetRowCellValue(i, "COL5") + "";
connection(sql); // sqlconnection and sqlcommand metod
}
Your code is wrong because you read your values NOT from the selected rows.
This should work:
int[] selectedrows = gridView1.GetSelectedRows();
foreach (int i in selectedrows)
{
string sql = "INSERT INTO dbo.TABLE1(COL1,COL2,COL3) SELECT " + gridView1.GetRowCellValue(i, "COL4") + "," + gridView1.GetRowCellValue(i, "COL5") + ",'" + gridView1.GetRowCellValue(i, "COL6")" FROM dbo.TABLE2 WHERE COL4=" + gridView1.GetRowCellValue(i, "COL4") + " AND COL5=" + gridView1.GetRowCellValue(i, "COL5") + "";
connection(sql); // sqlconnection and sqlcommand metod
}

C# ASP.NET (VS 2008 Exp) Database saves hebrew value from UPDATE as '?'

As I haven't found a solution to my previous question (Link), I am posting a new one, hoping for a solution. I'm sorry if I am breaking the rules, but I haven't received a solution.
when I try to update a row, and I have tracked what query is sent, for example:
UPDATE global_status SET title = 'Login_Failure', info = 'שדכ' WHERE id = '2'
So you can see that the final query which is sent is in Hebrew, so it's not a problem before that. I execute it this way:
string Status_Update = "UPDATE global_status SET title = '" + Title + "', info = '" + Info + "' WHERE id = '" + Request.Form["Status_Key"] + "'";
MyAdoHelper.DoQuery(GlobalVar.DatabaseName, Status_Update);
The method:
public static void DoQuery(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
com.ExecuteNonQuery();
com.Dispose();
conn.Close();
}
After the update, the database contains ??? where I inserted Hebrew letters.
I can manually insert Hebrew values into the database, and also get them back.
I have another form (registration) where I am able to insert Hebrew values, using the DoQuery();
Here is the source code for the update page (it's updating a title and info of a record, nothing special):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class admin_EditGlobalStatus : System.Web.UI.Page
{
public string StatusesTable;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["Status_Update"] != null)
{
string Title = Request.Form["Status_Title"].Secure();
string Info = Request.Form["Status_Info"].Secure();
Info = Info.Replace("/s", "<span class\"res\">").Replace("/e", "</span>");
string Status_Update = "UPDATE global_status SET title = '" + Title + "', info = '" + Info + "' WHERE id = '" + Request.Form["Status_Key"] + "'";
MyAdoHelper.DoQuery(GlobalVar.DatabaseName, Status_Update);
}
if (Request.Form["Status_Delete"] != null)
{
string Status_Delete = "DELETE FROM global_status WHERE id = '" + Request.Form["Status_Key"] + "'";
MyAdoHelper.DoQuery(GlobalVar.DatabaseName, Status_Delete);
}
string GetGlobalStatuses = "SELECT * FROM global_status";
DataTable dt = MyAdoHelper.ExecuteDataTable(GlobalVar.DatabaseName, GetGlobalStatuses);
if (dt.Rows.Count > 0)
{
StatusesTable = "<table cellspacing=\"15\">";
StatusesTable += "<th>כותרת ההודעה</th><th>מידע ההודעה</th>";
foreach (DataRow status in dt.Rows)
{
StatusesTable += "<tr><form method=\"post\" action=\"\">";
StatusesTable += "<input type=\"hidden\" name=\"Status_Key\" value=\"" + status["id"].ToString() + "\" />";
StatusesTable += "<td><input size=\"25\" dir=\"ltr\" type=\"text\" name=\"Status_Title\" value=\"" + status["title"].ToString() + "\" /></td>";
StatusesTable += "<td><input size=\"90\" type=\"text\" name=\"Status_Info\" value=\"" + status["info"].ToString().Secure() + "\" /></td>";
StatusesTable += "<td><input type=\"submit\" name=\"Status_Update\" value=\"עדכן\"><input type=\"submit\" name=\"Status_Delete\" value=\"מחק\"></td></form></tr>\r\n";
}
StatusesTable += "</table>";
}
else
{
StatusesTable = "<h1>אין משתמשים קיימים</h1>";
}
}
}
Hoping for a solution, Thanks!
Guy
After reading several text explanation I wound that many people are capable to solve the problem with N at the beginning of string like this
string Status_Update = "UPDATE global_status SET title = '" +
Title + "', info =N'" + Info + "' WHERE id = '" +
Request.Form["Status_Key"] + "'";
also make sure to try nvarchar or unicode

Categories

Resources