When I Using this command to insert data, it's totally working..
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
But, after I add or replace this command, "Syntax error in FROM clause" shows up..
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
This is full code-behind:
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con;
OleDbCommand cmd;
int Quan;
double TotalPrice;
//int i = 0;
string Date = DateTime.Now.ToString("dddd, dd MMMM yyyy");
protected void Page_Load(object sender, EventArgs e)
{
Lb_Date.Text = Date;
}
protected void bt_Calc_Click(object sender, EventArgs e)
{
Quan = Convert.ToInt32(tb_Quan.Text);
TotalPrice = Convert.ToDouble(Lb_Price.Text) * Quan;
Lb_TotalPrice.Text = TotalPrice.ToString();
}
protected void ddl_PizzaCode_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strquery = "SELECT * FROM Product WHERE ID = " + ddl_PizzaCode.SelectedValue;
using (con = new OleDbConnection(#"PROVIDER= Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE =C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(dt);
}
Lb_PizzaName.Text = dt.Rows[0]["Product_Name"].ToString();
Lb_Price.Text = dt.Rows[0]["Price_per_Unit"].ToString();
}
}
protected void btn_Save_Click(object sender, EventArgs e)
{
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
BindUserDetails();
}
protected void BindUserDetails()
{
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
string strquery = "SELECT * FROM Customer";
string strquery2 = "SELECT * FROM Transaction";
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds);
}
using (cmd = new OleDbCommand(strquery2, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds2);
}
}
}
}
The word DATE is a keyword in SQL Server, and thus needs to be in square brackets when you are using it as a field name in C#. This line should work:
cmd.CommandText = "insert into Transaction(Product_Code, [Date], Quantity, Total, Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
have you ever heard of SQL-Injection.... you are WIDE OPEN to exposure.
ALL your queries should have data cleaned and parameterized. Never concatenate what you can't control from the web.
Using parameters in your commands basically means using the proper character identifier indicating a parameter. In SQL and Access, you should be good with the "#" sign. Other databases use different parameters. VFP uses "?" as a place-holder, SAP Advantage Database uses ":".
Change your commands (all of them select, insert, update, delete) to something like..
cmd.CommandText =
#"insert into Customer
( Customer_Phone, Customer_Name )
VALUES
( #parmCustomerPhone, #parmCustomerName)";
cmd.Parameters.AddWithValue( "#parmCustomerPhone", tb_CustNum.Text );
cmd.Parameters.AddWithValue( "#parmCustomerName", tb_CustName.Text );
Then you should be good. Concatenation can fail if someone puts in a quote ' as part of a name, such as "O'Mally". The quote would mis-balance your quotes and cause failure.
If your columns are of numeric or date data types, make sure the parameter you are sending is of that type via the AddWithValue() call.
Additionally, for clarification, I am explicitly calling the values in the insert statement as "#parmSomething" so you know it is the parameter value, not the actual column name and avoiding confusion... especially as a beginner for web and querying.
Finally as noted by other. Be careful about reserved words such as date, time, and other sql clauses. These should be qualified or wrapped in brackets such as [Date] or Date
As for your multiple insert statements, SQL typically uses a semi-colon to identify the end of one statement and allow there to be multiple in a single call such as
cmd.CommandText =
#"insert into Transaction
( Product_Code,
[Date],
Quantity,
Total,
Customer_Phone )
values
( #parmPizza,
#parmNow,
#parmQty,
#parmPrice,
#parmPhone );
insert into Customer
( Customer_Phone,
Customer_Name )
VALUES
( #parmCustPhone,
#parmCustName ) ";
// NOW, add all the parameters...
cmd.Parameters.AddWithValue( "#eachParmAbove", respectiveTextDateNumericValue );
...
...
...
THEN execute it. Hopefully the readability of these samples helps you too.
Related
i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.
The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End
i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"
Hello I want to store datetimepicker value into mysql database my code is given below
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime + "','" + s + "','" + day + "','"+dtpDate+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but no value is being stored at database
and at that place there is unable to read data comes.
what may be the problem?
The Value is not being entered at MySQL database because there is mistake in your query at dtpTime and dtpDate fields.
you shout replace it whith dtpTime.Value.TimeofDay and dtpDate.Value.Date ane new query will be like this
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Well, it may not be the cause of the problem (are there any exceptions? What does ExecuteNonQuery return?) but you should definitely not be building up your SQL like this. It leads to SQL injection attacks, as well as data conversion problems.
Instead, you should use parameterized SQL:
using (MySqlConnection conn = new MySqlConnection(...))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(
"INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) " +
"VALUES (#name, #time, #status, #days, #date, #connector)", conn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#time", MySqlDbType.Time).Value = dtpTime;
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#days", MySqlDbType.Int32).Value = day;
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = dtpDate;
cmd.Parameters.Add("#connector", MySqlDbType.VarChar).Value = chkArray[i].Tag;
int insertedRows = cmd.ExecuteNonQuery();
// TODO: Validate that insertedRows is 1?
}
}
I've guessed at the data types - please check them against your actual database.
Using NuGet Package MySql.Data 6.6.4.
Currently MySqlParameter does not support unnamed parameters. Parameters must begin with with a ?.
Example:
command.Parameters.AddWithValue("?Parameter", value);
Something like this should work. Avoid string concatenation with Sql because that can lead to security risks.
dtpDate = datetimepicker1.value.date.ToString("yyyy-MM-dd HH:mm"); //Formatted Date for MySql
dtpTime = datetimepicker2.value.Timeofday;
using(var connection = new MySqlConnection(connectionString))
{
using(var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ( ?ScheduleName, ?StartTime, ?Status, ?Days, ?StartDate, ?ConnectorId )";
command.Parameters.AddWithValue("?ScheduleName", name);
command.Parameters.AddWithValue("?StartTime", dtpTime);
command.Parameters.AddWithValue("?Status", s);
command.Parameters.AddWithValue("?Days", day);
command.Parameters.AddWithValue("?StartDate", dtpDate);
command.Parameters.AddWithValue("?ConnectorId", chkArray[i].Tag);
connection.Open();
command.ExecuteNonQuery();
}
}
I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());