How to loop through textBox(i) in c#? - c#

I've a situation here . I haven't written the code , as I don't have the idea even to kick it off!. I've 10 textboxes and a button , so when I finish typing into only 3 I'll use only three as the values I'm parsing into these textboxes go into the database.I'm planning to write a query in a for loop and execute it, so that only the text boxes which have value get into the database.
for(int i=0;i<9;i++)
{
string sql = "Insert Into exprmnt(docid,itemid,doctitle,itemcontent)values("+int.Parse(label6.Text)+","+i+",'"+label5.Text+"','"+textBox[i].Text+"')";
}
OleDbCommand cmd = new OleDbCommand(sql,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this is something that I'd want to happen , it's okay if I've empty 'itemcontent' against some itemid 'i'which happens when I save all the text boxes including the ones that don't have any text keyed in.

To loop through textBox you can create an array of textBoxes you want to loop through:
TextBox[] tbs = {textBox1, textBox2, textBox3}; //put all into this array
for(int i = 0; i<tbs.Length; i++)
{
//use each textBox in here:
string text = tbs[0].Text; //this is an example of how to get the Text property of each textBox from array
}

For what it's worth, you can use Linq to find the filled textboxes. You're open for SQL-Injection. Use parameters instead of string concatenation:
int docid = int.Parse(label6.Text);
String doctitle = label5.Text;
var filledTextBoxes = this.Controls
.OfType<TextBox>()
.Select((txt,i) => new { Textbox = txt, Index = i })
.Where(x => x.Textbox.Text.Length != 0);
if(filledTextBoxes.Any())
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
const String sql = "Insert Into exprmnt(docid,itemid,doctitle,itemcontent)values(#docid, #itemid, #doctitle, #itemcontent)";
connection.Open();
foreach(var txt in filledTextBoxes)
{
OledDbCommand cmd = new OledDbCommand(sql, connection);
// Set the parameters.
cmd.Parameters.Add(
"#docid", OleDbType.Integer).Value = docid;
cmd.Parameters.Add(
"#doctitle", OleDbType.VarChar, 50).Value = doctitle;
cmd.Parameters.Add(
"#itemid", OleDbType.Integer).Value = txt.Index;
cmd.Parameters.Add(
"#itemcontent", OleDbType.VarChar, 100).Value = txt.Textbox.Text;
try
{
int affectedRecords = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
} // The connection is automatically closed when the code exits the using block.
}
Note that i've used the using-statement to ensure that the connection gets disposed(closed).

It worked finally!!!
#yogi thanks!
the code that worked is
List<TextBox> textBoxList = new List<TextBox>();
textBoxList.Add(new TextBox { Text = textBox1.Text });
textBoxList.Add(new TextBox { Text = textBox2.Text });
textBoxList.Add(new TextBox { Text = textBox3.Text });
textBoxList.Add(new TextBox { Text = textBox4.Text });
for (int n = 1; n<4; n++)
{
string sql = "Insert Into exprmnt (docid,itemid,doctitle,itemcontent) values(" + int.Parse(label6.Text) + "," + n + ",'" + label5.Text + "','" + textBoxList[n].Text+ "')";
OleDbCommand cmd = new OleDbCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
}

Add your textbox controls to a list.. then loop over the list.
List<TextBox> textBoxList = new List<TextBox>();
for (int i = 0; i < textBoxList.Count; i++) {
// .. do your thing here, using textBoxList[i].Text for the value in the textbox
}
Also, as Tim Schmelter pointed out.. you're open for SQL injection when concatenating your queries like that.

Related

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Retrieve Rows Value to Textboxes C# & SQL Server

Do you have any ideas on how I can put this to rows:
in this texboxes?
or sooner 10 rows to 10 textboxes?
I only know is to retrieve one row:
if (Inventory.passQty == "1")
{
SqlConnection connection = new SqlConnection("Data Source = DESKTOP-ANJELLO\\SQLEXPRESS; Initial Catalog = db_ADAPurchase; Persist Security Info = True; User Id = sa; Password = mm4;");
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT * FROM tbl_PurchaseRequest WHERE request_id = {0}", Inventory.passID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label_RID.Text = dr.GetString(0);
label_Item1.Text = dr.GetString(1);
txb_Title.Text = dr.GetString(2);
cbx_vendor.Text = dr.GetString(3);
txb_address.Text = dr.GetString(4);
label_date.Text = dr.GetString(5);
cbx_terms.Text = dr.GetString(6);
txb_ITD1.Text = dr.GetString(7);
txb_Qty1.Text = dr.GetSqlInt32(8).ToString();
label_unit1.Text = dr.GetString(9);
txb_UntP1.Text = dr.GetSqlInt32(10).ToString();
txb_TotP1.Text = dr.GetSqlInt32(11).ToString();
label_total.Text = dr.GetSqlInt32(12).ToString();
txb_reqBy.Text = dr.GetString(13);
}
connection.Close();
}
How do I make this to retrieve multiple rows in different textboxes?
Thanks for helping me!
PS: Sir #mohit-shrivastava can you please help me again?🙏
You can do something like this but GridView is instead a very good idea to implement this kind of situation.
if (Inventory.passQty == "1")
{
SqlConnection connection = new SqlConnection("Data Source = DESKTOP-ANJELLO\\SQLEXPRESS; Initial Catalog = db_ADAPurchase; Persist Security Info = True; User Id = sa; Password = mm4;");
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("SELECT * FROM tbl_PurchaseRequest WHERE request_id = {0}", Inventory.passID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
label_RID.Text = dr.GetString(0);
label_Item1.Text = dr.GetString(1);
txb_Title.Text = dr.GetString(2);
cbx_vendor.Text = dr.GetString(3);
txb_address.Text = dr.GetString(4);
label_date.Text = dr.GetString(5);
cbx_terms.Text = dr.GetString(6);
label_total.Text = dr.GetSqlInt32(12).ToString();
txb_reqBy.Text = dr.GetString(13);
int number = 1;
do
{
TextBox tb = this.Controls.Find("txb_ITD" + number.ToString(), true).FirstOrDefault() as TextBox;
tb.Text = dr.GetString(7);
TextBox tb1 = this.Controls.Find("txb_Qty" + number.ToString(), true).FirstOrDefault() as TextBox;
tb1.Text = dr.GetSqlInt32(8).ToString();
TextBox tb2 = this.Controls.Find("label_unit" + number.ToString(), true).FirstOrDefault() as TextBox;
tb2.Text = dr.GetString(9);
TextBox tb3 = this.Controls.Find("txb_UntP" + number.ToString(), true).FirstOrDefault() as TextBox;
tb3.Text = dr.GetSqlInt32(10).ToString();
TextBox tb4 = this.Controls.Find("txb_TotP" + number.ToString(), true).FirstOrDefault() as TextBox;
tb4.Text = dr.GetSqlInt32(11).ToString();
number++;
//Since Query can pull more records than 10
if(number>=10)
{
break;
}
}
while(dr.Read())
}
connection.Close();
}
This code will read the SQL Data as the way you were reading it and then fill all the textboxes which are supposed to be printed once. Liek RequestID, Item, Title, Vendor etc.. then comes to the loop. Now dr already have the first record so we dont want to read the dr again otherwise it will take the next record in the record set so we used do-while instead of while. Now We are trying to find the controls from Control.ControlCollection.Find and put the extracted values to the concerning textboxes.
Note: The Code has not been tested. but it is to give you the glimpse of what has to be done to get the output as expected.
i think for creating multiple rows by creating multiple server side textbox.you neeed jquery for that. that is much easy faster and reliable:
Steps You required :
1.Create a webservice that pull all rows from the database.
2.Bind table rows by loping the data from webservice.
3.Create a webservice to insert all data to databse.

database values in textbox

If the voucher number that I typed exists in the table, it should show the details in the respective textboxes, but if it doesn't exist a message box that says (ID doesn't exists! ) would show.
For example, the voucher number 101 exists in the table,
First,I would type '1' in the textbox , the messagebox would immediately appear ...
Second I would continue the number after clicking ok it will now be number "10" a messagebox will again appear that says (ID doesn't exists! ). Then finally I would be able to type "101" the details would already show in the respective textboxes.
My problem is that when everytime that I typed a single number, a messagebox that says (ID doesn't exists! ) appears. How do I solve that?
textchanged property of "textBox22" code:
private void textBox22_TextChanged(object sender, EventArgs e)
{
String path = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlconn = new MySqlConnection(path); //communicator //constructors
MySqlCommand sqlcomm = new MySqlCommand();
MySqlDataReader sqldr;
sqlconn.Open();
sqlcomm.Connection = sqlconn;
sqlcomm.CommandType = CommandType.Text;
sqlcomm.CommandText = "Select * from approvedrecords where VoucherNumber=" + textBox22.Text + "";
sqldr = sqlcomm.ExecuteReader();
sqldr.Read();
if (sqldr.HasRows)
{
textBox26.Text = sqldr[0].ToString();
}
sqlconn.Close();
if (textBox22.Text == textBox26.Text)
{
String path8 = "Data Source=LOCALHOST; Initial Catalog= sadd; username=root; password=''";
MySqlConnection sqlcon = new MySqlConnection(path8); //communicator //constructors
string query = "select * from approvedrecords where VoucherNumber = " + textBox22.Text + " ";
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataReader dbr;
sqlcon.Open();
dbr = cmd.ExecuteReader();
while (dbr.Read())
{
string a = (string)dbr["CheckNumber"].ToString();
string b = (string)dbr["DateCreated"];
string c = (string)dbr["Status"];
string d = (string)dbr["PayeesName"];
string f = (string)dbr["Amount"].ToString();
string g = (string)dbr["DatePrinted"];
string h = (string)dbr["Particulars"];
string i = (string)dbr["Prepared_by"];
string j = (string)dbr["Payment_received_by"];
textBox21.Text = a;
textBox23.Text = b;
textBox28.Text = c;
textBox20.Text = d;
textBox19.Text = f;
textBox27.Text = g;
textBox18.Text = h;
textBox16.Text = i;
textBox17.Text = j;
}
}
else
{
MessageBox.Show("ID doesn't exist!");
}
Why don't you try using the OnLostFocus event of the textbox? As explained here. That way your code would be called only when the user abandons your textbox.
Alternatively, if you want to keep your OnTextChanged handler, I would recommend using async calls my adding an UpdatePanel as explained here. You would need to add a label showing the status of the query every time the user typed in a character, so when no data is returned by your query, the label would show "No results found for this ID" and no textboxes would be populated. When results are found, then the label would read "Data was found for this ID" and you would populate the controls accordingly.
I hope this helps and I hope I was clear :-)

Taking values into an array of textboxes (ASP.NET using C#)

So I have an array of textboxes dynamically appear (The number of textboxes depends upon how a number from a database). They draw to the screen just fine.
i = 0;
while (i < size)
{
pnlTxtBoxes.Controls.Add(labels[i]);
pnlTxtBoxes.Controls.Add(txtBoxes[i]);
pnlTxtBoxes.Wrap = true;
i++;
}
Like I said, the textboxes appear and the labels are displaying correctly. But when I go to retrieve the text from them, I get the error "Object reference not set to an instance of an object."
i = 0;
while (i < size)
{
values[i] = txtBoxes[i].Text;
txtBoxes[i].Visible = false;
labels[i].Visible = false;
i++;
}
Does anybody have an idea as to why I'm getting this error (and what I can do to fix it)?
EDIT: Here is all of the code. This is just a development DB, so I am not worried about showing the password
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
public partial class dieClearanceCalc : System.Web.UI.Page
{
static string connectionString = "database=localhost;database=matedevdb;uid=dev;pwd=123;";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT shapeName FROM tblShapes;");
MySqlDataReader reader;
int size;
TextBox[] txtBoxes;
Label[] labels;
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = con;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
shapeSelection.Items.Add(reader.GetString(0));
}
reader.Close();
}
catch (Exception ex)
{
Response.Write("<p style='Color:red'>Error:<br/>" + ex + "</p>");
}
}
protected void shapeSelected(object sender, EventArgs e)
{
string[] labelTxt;
int i = 0;
//Make current elements invisable
lblShape.Visible = false;
shapeSelection.Visible = false;
btnSelectShape.Visible = false;
// find the size of the arrays
cmd.CommandText = "SELECT COUNT(varID) FROM tblVariables WHERE shapeID IN(SELECT shapeID FROM tblShapes WHERE shapeName= '" + shapeSelection.SelectedValue + "')";
reader = cmd.ExecuteReader();
if (reader.Read())
{
size = reader.GetInt32(0);
}
reader.Close();
labelTxt = new string[size];
labels = new Label[size];
txtBoxes = new TextBox[size];
// gather the labels from the db
cmd.CommandText = "SELECT varDesc FROM tblVariables WHERE shapeID IN(SELECT shapeID FROM tblShapes WHERE shapeName= '" + shapeSelection.SelectedValue + "')";
reader = cmd.ExecuteReader();
i = 0;
while (reader.Read())
{
labelTxt[i] = reader.GetString("varDesc");
i++;
}
reader.Close();
i = 0;
while (i < size)
{
labels[i] = new Label();
txtBoxes[i] = new TextBox();
labels[i].Text = labelTxt[i];
i++;
}
i = 0;
while (i < size)
{
pnlTxtBoxes.Controls.Add(labels[i]);
pnlTxtBoxes.Controls.Add(txtBoxes[i]);
pnlTxtBoxes.Wrap = true;
i++;
}
btnSendData.Visible = true;
//Response.Write(size); test to see if the size variable is working
Response.Write(size);
}
protected void calc(object sender, EventArgs e)
{
//declarations
formula diagonal, periphery;
string dFormula = "", pFormula = "";
string[] variables;
string[] values;
int i = 0;
//end of declarations
// This value must be retrievd again, because somewhere size is getting a value of 0
cmd.CommandText = "SELECT COUNT(varID) FROM tblVariables WHERE shapeID IN(SELECT shapeID FROM tblShapes WHERE shapeName= '" + shapeSelection.SelectedValue + "')";
reader = cmd.ExecuteReader();
if (reader.Read())
{
size = reader.GetInt32(0);
}
reader.Close();
variables = new string[size];
values = new string[size];
i = 0;
while (i < size)
{
values[i] = txtBoxes[i].Text;
txtBoxes[i].Visible = false;
labels[i].Visible = false;
i++;
}
btnSendData.Visible = false;
// retrieve the diagonal formula from the db
cmd.CommandText = "SELECT diagonalFormula, peripheryFormula FROM tblShapes WHERE shapeName='" + shapeSelection.SelectedValue + "'";
reader = cmd.ExecuteReader();
while (reader.Read())
{
dFormula = reader.GetString("diagonalFormula");
pFormula = reader.GetString("peripheryFormula");
}
reader.Close();
Response.Write(size);
// gather the variable names from the db
cmd.CommandText = "SELECT varName FROM tblVariables WHERE shapeID IN(SELECT shapeID FROM tblShapes WHERE shapeName= '" + shapeSelection.SelectedValue + "')";
reader = cmd.ExecuteReader();
while (reader.Read())
{
variables[i] = reader.GetString("varName");
i++;
}
reader.Close();
con.Close();
diagonal = new formula(dFormula, variables, values);
periphery = new formula(pFormula, variables, values);
txtDiagonal.Visible = true;
txtPeriphery.Visible = true;
txtDiagonal.Text = diagonal.getEquation();
txtPeriphery.Text = periphery.getEquation();
}
public static double Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
System.Data.DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
}
I reckon you initialize the labels and txtBoxes in if IsPostBack block and don't save it in ViewState or Session.
Edit:
saw your code labels and txtBoxes was initialized in shapeSelected method. same problem will happen: they are lost between postback.
So they are empty in event handler when postback because whole Page object was re-created when postback. Asp.net runtime helps to load content from ViewState for control.But for class member variable you have to maintain by yourself.like:
public string NavigateUrl
{
get
{
string text = (string) ViewState["NavigateUrl"];
if (text != null)
return text;
else
return string.Empty;
}
set
{
ViewState["NavigateUrl"] = value;
}
}
Above code comes from:
Understanding ASP.NET View State
http://msdn.microsoft.com/en-us/library/ms972976.aspx
The article also introduces View State and Dynamically Added Controls
An important thing to remember when programming with ASP.NET is that your whole object model on a page gets created with every web request again and again. This means that if you add some controls to you page dynamically in an event that does not happen each page load they are not going to survive the postback if you don't add them again somehow.
You can read about Asp.Net page Life Cycle here: http://msdn.microsoft.com/en-us/library/ms178472.aspx
I don't think there is a standard way to solve your problem, but what you are trying to do can be achieved in several ways. One was already mentioned to you - usage of ViewState. Another one would be hitting database on each post back, and making sure you are recreating the controls each time the page is served. One more way is to somehow encode the data that is required for recreating your controls and make sure that they are passed with each post back. The latter is essentially what ViewState does, but you can do it more efficiently if you want to reduce the size of you ViewState, and thus size in bytes of your postback and page.
Without seeing more code, I can only guess that the problem lies with where you populate the txtBoxes[] array. Make sure there are no null values in that array.

replace method mechanism

i face the following problem::
i wanna to escape the following character ' single quote:
it works when making this test through :the built in method Replace("'","''");
as this code below :(just a test) it works
protected void btn_insert_Click(object sender, EventArgs e)
{
lbl.Text = string.Empty;
SqlConnection mycon = new SqlConnection(Constr);`
SqlCommand mycommand = new SqlCommand("INSERT INTO details VALUES('" + txt.Text.Replace("'", "''") + "','" + txt.Text.Replace("'", "''")+ "')", mycon);
mycon.Open();
int affectedRows = 0;
affectedRows = mycommand.ExecuteNonQuery();
mycon.Close();
}
but i wanna to generalize my solution to work all over the application through my Insert method in the data access layer:
public static int InsertEntity(string tblName, Dictionary<string, string> dtParams)
{
int Result = -1;
DBConnection DAL_Helper = new DBConnection("");
string[] field_names = new string[dtParams.Count];
dtParams.Keys.CopyTo(field_names, 0);
string[] field_values = new string[dtParams.Count];
dtParams.Values.CopyTo(field_values, 0);
for (int i = 0; i < field_values.Length; i++)
{
field_values[i].Replace("'", "''");
}
string insertCmd = "INSERT INTO " + tblName + " (" + string.Join(",", field_names) + ") values ('" + string.Join("','", field_values) + "')";
Result = DAL_Helper.Execute_NonQuery(insertCmd);
return Result;
}
this not escaping the ' single quote charecter,although i use Replace("'","''");
what is the problem ,,how to fix this problem?
I strongly recommend you use Command Parameters using SqlCommand.Parameters collection instead of your approach.
Problem is here :
for (int i = 0; i < field_values.Length; i++)
{
field_values[i].Replace("'", "''");
}
Replace it with :
for (int i = 0; i < field_values.Length; i++)
{
field_values[i] = field_values[i].Replace("'", "''");
}
Building on decyclone's answer. CommandParameters are the way to go here, you are just re-inventing it with your own code.
I have found a very nice clear example here for supplying params to a SQL statement.
http://dotnetperls.com/sqlparameter
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
string dogName = "Mc'Dougal";
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
}

Categories

Resources