Saving Data from a gridview into a local database in asp.net - c#

I am currently writing a piece of code where the user is supposed to insert a few information about an employee and press one button populate for populating a gridview and another one to save the information in gridview into a local database. While running the what I wrote so far there is a consistent error saying "SqlExeption was unhandled by the user code. I have been trying to fix it but without success. It complains on conn.Open();
This is that specific piece of code:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(#"Data Source = C:\EmployeeWebProject\EmployeeWebProject\App_Data\EmployeeDatabase.sdf"))
{
using (SqlCommand comm = new SqlCommand("SELECT * FROM Employee"))
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO Employee VALUES ("
+ GridView1.Rows[i].Cells[0].ToString() + ", "
+ GridView1.Rows[i].Cells[1].ToString() + ", "
+ GridView1.Rows[i].Cells[2].ToString() + ", "
+ GridView1.Rows[i].Cells[3].ToString() + ", "
+ GridView1.Rows[i].Cells[4].ToString() + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
finally
{
}
}

To avoid SQL injection and use properly parametrized queries, and also use the SQL Server CE connection and command objects, try this code:
protected void SaveButton_Click(object sender, EventArgs e)
{
string StrQuery;
try
{
// define connection string and INSERT query WITH PARAMETERS
string connectionString = #"Data Source = C:\EmployeeWebProject\EmployeeWebProject\App_Data\EmployeeDatabase.sdf";
string insertQry = "INSERT INTO Employees(Col1, Col2, Col3, Col4, Col5) " +
"VALUES(#Col1, #Col2, #Col3, #Col4, #Col5);";
// define connection and command for SQL Server CE
using (SqlCeConnection conn = new SqlCeConnection(connectionString))
using (SqlCeCommand cmd = new SqlCeCommand(insertQry, conn))
{
// add parameters to your command - adapt those *as needed* - we don't know your table structure,
// nor what datatype (and possibly length) those parameters are !
cmd.Parameters.Add("#Col1", SqlDbType.Int);
cmd.Parameters.Add("#Col2", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col3", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col4", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#Col5", SqlDbType.VarChar, 100);
conn.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
// set parameter values
cmd.Parameters["#Col1"].Value = Convert.ToInt32(GridView1.Rows[i].Cells[0]);
cmd.Parameters["#Col2"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col3"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col4"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.Parameters["#Col5"].Value = GridView1.Rows[i].Cells[1].ToString();
cmd.ExecuteNonQuery();
}
}
}
finally
{
}
}

Related

Insert text file data into SQL Server database table of specific column

I have attached my code in which I tried to read a .txt file with many records.
The same text file data I need to insert into the SQL Server database table in specific columns. Here is the code I wrote by taking reference from some where.
protected void BtnUpload_Click(object sender, EventArgs e)
{
FileUpload(x);
}
private void FileUpload(List<string> x)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand();
string fileName = Path.Combine(#"C:\Users\user\Desktop\SBS", FileUpload1.FileName);
if(FileUpload1.HasFile)
{
try
{
con.Open();
List<string> x;
for (int i = 0; i <= x.Count - 9; i += 9)
{
SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
string.Format("Values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}')", x[i], x[i + 1], x[i + 2], x[i + 3], x[i + 4], x[i + 5], x[i + 6], x[i + 7], x[i + 8], x[i + 9]), con);
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
}
example of my file :
1 |abc| |bcd| |101|
here | denoted separator of column and yes every line should be inserted in the table where in specific column is available
Can anyone help me to insert file data into the SQL Server table?
Please help me to solve the issue
I wouldn't use a program at all... I'd use the "Import" feature in SQL server to import a pipe-delimited file. For example How to import pipe delimited text file data to SQLServer table
Here is an example of working code that will read data from a Text file, where that data is delimited by |. Multiple insert statements will be executed within a single transaction, in case of failure using an All Or Nothing principle.
[TestMethod]
public void TestInsertDataFromFile()
{
String fileName = #"D:\SampleData.txt";
String connectionString = #"Server=MyTestDBServer; Database=TestingDatabase; Trusted_Connection=True;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction transaction = conn.BeginTransaction())
{
String insertCommand = #"INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) ";
insertCommand += #"VALUES (#sbsBranchCode, #branchName, #finYear, #brChallanNo, #transDate, #majorHead, #receiptPayment, #amount, #planNonPlan)";
String[] fileContent = File.ReadAllLines(fileName);
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = insertCommand;
command.CommandType = CommandType.Text;
command.Transaction = transaction;
foreach (String dataLine in fileContent)
{
String[] columns = dataLine.Split('|');
command.Parameters.Clear();
command.Parameters.Add("sbsBranchCode", SqlDbType.VarChar).Value = columns[0];
command.Parameters.Add("branchName", SqlDbType.VarChar).Value = columns[1];
command.Parameters.Add("finYear", SqlDbType.VarChar).Value = columns[2];
command.Parameters.Add("brChallanNo", SqlDbType.VarChar).Value = columns[3];
command.Parameters.Add("transDate", SqlDbType.VarChar).Value = columns[4];
command.Parameters.Add("majorHead", SqlDbType.VarChar).Value = columns[5];
command.Parameters.Add("receiptPayment", SqlDbType.VarChar).Value = columns[6];
command.Parameters.Add("amount", SqlDbType.VarChar).Value = columns[7];
command.Parameters.Add("planNonPlan", SqlDbType.VarChar).Value = columns[8];
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
}
Important things to note
NEVER have an empty catch {} handler as you will never know if there are problems.
When talking to the database using externally specified values, ALWAYS use parameters to prevent SQL Injection attacks.
Make use of Transactions if you are doing multiple inserts from a single source. It will make recovery possible without having to unpick the data manually.
Where possible (when classes implement IDisposable) use a using(...) block to ensure resources are released and not blocking/locking.
use this code:
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand();
string fileName = Path.Combine(#"C:\Users\user\Desktop\SBS", FileUpload1.FileName);
if (FileUpload1.HasFile)
{
var lines = File.ReadAllLines(fileName);
try
{
con.Open();
foreach (var line in lines)
{
var columns = line.Split('|');
SqlCommand myCommand = new SqlCommand("INSERT INTO SBSFile (SBSBranchCode, BranchName, FinYear, BrChallanNo, TransDate, MajorHead, ReceiptPayment, Amount, PlanNonPlan) " +
$"Values('{columns[0]}', '{columns[1]}','{columns[2]}','{columns[3]}','{columns[4]}','{columns[5]}','{columns[6]}','{columns[7]}','{columns[8]}''{columns[9]}')");
myCommand.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
}
}

Invalid column name? c# sql

Why isnt this working? it says invalid column name when i try to remove something after i added it
private void btnRemoveCommand_Click(object sender, EventArgs e)
{
connection = new SqlConnection(connectionString);
connection.Open();
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
var sql = "DELETE FROM Commands WHERE commandName = " + listBox1.SelectedItems[i] + "";
listBox1.Items.Remove(listBox1.SelectedItems[i]);
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.ExecuteNonQuery();
}
connection.Close();
}
this is the event that handles the addCommand to the database
private void btnAddCommand_Click(object sender, EventArgs e)
{
var sql = "INSERT INTO Commands(commandName, pathToCommand) VALUES(#commandName, #pathToCommand)";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("#commandName", tbxCommand.Text);
cmd.Parameters.AddWithValue("#pathToCommand", tbxPathToCommand.Text);
int affectedRows = cmd.ExecuteNonQuery();
}
}
Change
var sql = "DELETE FROM Commands WHERE commandName = " + listBox1.SelectedItems[i] + "";
to
var sql = "DELETE FROM Commands WHERE commandName = '" + listBox1.SelectedItems[i] + "'";
First thing is first, always always, always use parameterised queries. No exceptions. Ever.
Next, use using blocks for objects that implement iDisposable, to ensure your unmanaged resources are properly cleaned up.
Finally, when removing items from the a collection you should to iterate in reverse to ensure you don't skip over any items:
private void btnRemoveCommand_Click(object sender, EventArgs e)
{
for (int i = listBox1.SelectedItems.Count; i >= 0; i--)
{
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("DELETE FROM Commands WHERE commandName = #Command;", connection))
{
connection.Open();
//Add parameter with Add method - you may need to address the data type
command.Parameters.Add("#Command", SqlDbType.VarChar, 50).Value = listBox1.SelectedItems[i];
command.ExecuteNonQuery();
}
listBox1.Items.Remove(listBox1.SelectedItems[i]);
}
}
This is still not ideal, because if you have 1000 items, you are executing 1000 queries. My preferred way of doing this is with table valued parameters. The first step would be to create a table type in the database. I tend to use generic naming for ease of reuse:
CREATE TYPE dbo.ListOfString AS TABLE (Value NVARCHAR(MAX));
Then you can pass this type to your query to delete the records
private void btnRemoveCommand_Click(object sender, EventArgs e)
{
var table = new DataTable();
table.Columns.Add("Value", typeof(string));
for (int i = listBox1.SelectedItems.Count; i >= 0; i--)
{
table.Rows.Add(new []{listBox1.SelectedItems[i]});
listBox1.Items.Remove(listBox1.SelectedItems[i]);
}
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("DELETE FROM Commands WHERE commandName IN (SELECT Value FROM #Commands);", connection)
{
connection.Open();
command.Parameters.Add(new SqlParameter("#Commands", SqlDbType.Structured) { Value = table, TypeName = "dbo.ListOfInt" });
command.ExecuteNonQuery();
}
}
Now you send a single command to the database, which is more efficient than sending multiple commands.

How can I insert and save data into database using Visual Studio and C#?

public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string q2 = "insert into gym.dbo.customer (name, weight, height, add_class, gender, fees) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "','" + this.comboBox1.Text + "','" + this.comboBox2.Text + "','" + this.comboBox3.Text + " ') ;";
SqlConnection con = new SqlConnection(ss);
SqlCommand cmd = new SqlCommand(q2, con);
SqlDataReader read;
try
{
con.Open();
read = cmd.ExecuteReader();
MessageBox.Show("Welcome to our gym");
while (read.Read()) { };
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can I insert and save data into the database using Visual Studio and C#?
This code throws an error. Anyone please give the suggestion to me to solve the error.
image description
At first make sure your the data type of different column of customer table.
Then make sure what type of data you have to save for combobox.
you have to get the selected value from your Combobox. combobox1,combobox2,combobox3 retuns only the class name
System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
You can follow this example
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
The comments are getting a bit busy, so this is the sort of thing you need to do (including parameterising the query):
Specifically, you don't need a reader for an insert statement as it doesn't return a result set.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
var sql = "insert into dbo.customer ...";
using (var con = new SqlConnection(ss))
{
var cmd = new SqlCommand(sql , con);
con.Open();
cmd.ExecuteScalar();
MessageBox.Show("Welcome to our gym");
}
}
Hi check that customer table is available in gym Database.
else try this link
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into customer (name,weight,height,add_class,gender,fees) values(#name,#weight,#height,#add_class,#gender,#fees)", con);
cmd.Parameters.AddWithValue("name", this.textBox1.Text);
if (con.State == ConnectionState.Closed)
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I found that your connection string declaration is wrong
public string ss = "Data Source=D\\SQLEXPRESS;Initial Catalog=gym;Integrated Security=True";
need to update like below
public string ss = "Data Source=abc\\SQLEXPRESS;Initial Catalog=gym; user id=sa; Password=123456";
Data source will be not be D, It should be Server name.
enter image description here

Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)

I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());

What is the optimal / standard method of using a sql connection?

protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
The first function gets all the table data and dumps it to a gridview.
The second function takes input and inserts it into the database.
How can these functions be condensed or simplified?
How can these functions be condensed or simplified?
I would focus on correctness before simplification. Currently I can see at least two problems with the code:
You should absolutely use parameterized SQL instead of putting the values into the SQL itself. Your current code is prone to SQL injection attacks.
You should use using statements so that connection and command are both closed automatically even if exceptions are thrown.
Then in terms of simplification:
You can use the SqlCommand constructor which takes the text and connection - the type defaults to Text anyway.
I would personally try to separate the UI code from the storage code, at least for a non-trivial project. You should look at ASP.NET MVC, at least to get some idea of separation, even if you don't change to start using it.
In Button2_Click(object sender, EventArgs e) method , you need to use parametrized query to avoid SQL Injection.
That is the standard way.
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (
studentID, studentFirstName, studentLastName
) VALUES (
#studID, #FName, #LName
)";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Parameters.AddWithValue("#studID", TextID.Text);
cmd.Parameters.AddWithValue("#FName", TextFirstName.Text);
cmd.Parameters.AddWithValue("#LName", TextLastName.Text);
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
Hope Its Helpful.

Categories

Resources