Displaying the values of listview in textboxes - c#

I'm creating an application in Visual Studio 2010 C# and MySQL where the user can add, edit, view an employee. I already done with adding and viewing part. However I'm little confused in editing. I have this listView in my form where it displays all the employee added to the database. What I want is that whenever the user will select an employee and click edit button I want the values saved in the database to show in the corresponding textboxes below the listView. Can someone give me any idea how to do this? Please
Screenshot:
Code for listView:
private void getEmployee()
{
listViewEmployee.Items.Clear();
string cmd = "select employee_number, employee_lastname, employee_firstname, employee_middlename, employee_position, employee_datehired from employee";
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
foreach (DataRow row in tbl.Rows)
{
ListViewItem lv = new ListViewItem(row[0].ToString());
lv.SubItems.Add(row[1].ToString() + ", " + row[2].ToString() + " " + row[3].ToString());
lv.SubItems.Add(row[4].ToString());
lv.SubItems.Add(row[5].ToString());
listViewEmployee.Items.Add(lv);
}
}
private void textBoxSearchEmployee_TextChanged(object sender, EventArgs e)
{
string cmd = "SELECT employee_number, employee_lastname, employee_firstname, employee_middlename, employee_position, employee_datehired FROM employee where employee_lastname Like '" + textBoxSearchEmployee.Text + "%'";
listViewEmployee.Items.Clear();
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
foreach (DataRow row in tbl.Rows)
{
ListViewItem lv = new ListViewItem(row[0].ToString());
lv.SubItems.Add(row[1].ToString() + ", " + row[2].ToString() + " " + row[3].ToString());
lv.SubItems.Add(row[4].ToString());
lv.SubItems.Add(row[5].ToString());
listViewEmployee.Items.Add(lv);
}
}

It seems to me you are able to populate the listView only.
A few pointers:
1) The way you're writing your SQL statement now is prone to SQL Injection. Use parameters in your SQL commands instead of directly concatenating the variables to your query. See this question for an example on how to do it.
2) Depending on where your other relevant data is located (i.e. if your database is normalized), you might have to do a join in your query.
string sqlQuery = "SELECT * FROM employee
JOIN other_employee_data_table on other_employee_data_table.employeeID = employee.ID
WHERE employee.employee_lastname LIKE #employee_lastname +'%'"
But if your employee table contains all the data, then no need to do a join. Just get all the relevant information from that table.
3) Once you got all the information you need, it's just a matter of reading those data and assigning them to their respective fields.
Pseudo Code:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = sqlQuery;
command.CommandType = System.Data.CommandType.Text;
// add parameters in this line
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// iterate in each row
for (int i = 0; i < reader.FieldCount; i++)
{
// iterate each column using reader.GetValue(i)
}
}
}
}

When the user presses the "edit" button...
Retrieve the selected employee
Use a SELECT to get the selected employee's information
Populate the text boxes with the selected employee's information
For example,
String employee = listViewEmployee.Text;
String cmd = "SELECT * FROM employee WHERE employee_lastname='" + employee + "'";
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(cmd);
txtLastName.Text = tbl.Rows[0][0];
// ...
// etc.
Note: It's a bad idea to concatenate values into a SQL query because if the values are malicious, a different query could be executed. For example, if employee had the value of x' OR '1'='1; DROP TABLE employee; -- or something along those lines, then the employee table could be dropped. The way around this is using Stored Procedures or parameterized queries.

Related

C# Data grid view, SQL Server: Select multiple Rows then insert selected rows with specified columns into SQL table

In my current application I have a snippet of code that allows me to select a single row in a data grid view and store all the columns information into a variable to do with what I want. I use this primarily to send information from one SQL database table to another. It's great for only sending specified cells within a row.
Here is how I do a single row:
string ID = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;
string itemOne= dataGridView1.SelectedRows[0].Cells[1].Value + string.Empty;
string itemTwo= dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;
string itemThree= dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
var vItemOne = itemOne;
var vItemTwo= itemTwo;
var vItemThree= itemThree;
// ETC..
However, I now want to be able to select Multiple Rows and only insert specified columns within those rows to a SQL database.
I've tried modifying the above code to work... obviously it doesn't work.
I believe I need a loop, I haven't really used loops much so I'm not sure how to make it loop, skip certain columns, then insert into database.
This is what I am currently attempting, however I seem to be messing up somewhere.
using (SqlConnection con = new SqlConnection(Connection.MTRDataBaseConn))
{
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO dbo.[" + txtJobName.Text + "] ([Item One], [Item Two], [Item Three]) VALUES(#ItemOne,#ItemTwo,#ItemThree)";
cmd.Connection = con;
string strItemOne = this.dataGridView1.SelectedRows[i].Cells[1].Value + string.Empty;
string strItemTwo = this.dataGridView1.SelectedRows[i].Cells[2].Value + string.Empty;
string strItemThree = this.dataGridView1.SelectedRows[i].Cells[3].Value + string.Empty;
//Parameters
cmd.Parameters.AddWithValue("#ItemOne", strItemOne);
cmd.Parameters.AddWithValue("#ItemTwo", strItemTwo);
cmd.Parameters.AddWithValue("#ItemThree", strItemThree);
//execute
cmd.ExecuteNonQuery();
//close connection
con.Close();
}
}
...
While Debugging My dataGridView.SelectedRows.Count; i++ doesn't seem to be increasing and is staying at 0... I'm receiving the error when I try to return the selected row to a string. Shouldn't my selected rows still return a value?
I'm under the assumption my loop is wrong.
Can anyone help me with my issue?
Simply have to use a for each statement
string itemOne= dataGridView1.SelectedRows[0].Cells[1].Value + string.Empty;
string itemTwo= dataGridView1.SelectedRows[0].Cells[2].Value + string.Empty;
string itemThree= dataGridView1.SelectedRows[0].Cells[3].Value + string.Empty;
var vItemOne = itemOne;
var vItemTwo= itemTwo;
var vItemThree= itemThree;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
//Insert Query Here
}

Show data in Textboxes from database in C#

Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error

How to read the column SqlDataReader

I am working on my windows form applications. In this winform, I have a checkListBox which binded the data from my sql db. I am trying to match the checkListBox's checkedItem to my sql table column's text which is stored as a nvarchar data type. I ran the debug mode and found out that it skip the entire while loop when the program is executed. I have no idea why because the valuable name items did actually showed which checkbox in checkListBox is checked
This is my code.
foreach(var items in checkListBox1.CheckedItems){
string query = "select * from my_table WHERE employeeName = '"+items+"'"
SqlCommand myCommand = new SqlCommand(query, myConn);
SqlDataReader dr = myCommand.ExecuteReader();
while(dr.Read()){
//read the column
}
}
Here is the screen Shot. I tried to fetch the chineseName in the column (don't worry about what it is lol)
You have multiple problems in your code. You don't need to write your query in ForEach loop. And if you are expecting to get multiple values from your checklistbox then equalto = operator is not your friend, you would need to use IN operator. Now check below example.
private void button1_Click(object sender, EventArgs e)
{
string items = string.Empty;
foreach (var item in checkedListBox1.CheckedItems)
{
if (items.Length == 0)
items = item.ToString();
else
items = items + "," + item;
}
//make myCommand object and open connection on your own
myCommand = new SqlCommand(query, myConn);
string query = #'select distinct firstName, lastName, chineseName, teacherEmail, entryYear, leaveYear, userLoginId, ad.applicationId
from [teacher_detail] as td
LEFT JOIN[class_detail] as cd ON td.teacherId = cd.teacherId
LEFT JOIN[application_teacher] as at ON at.teacherId = td.teacherId
LEFT JOIN[application_detail] as ad ON at.applicationId = ad.applicationId
Where ad.applicationId = 2
and chineseName in (#name)'
myCommand.Parameters.Add("#name", SqlDbType.nvarchar);
myCommand.Parameters["#name"].Value = items;
//now execute query
}
As Data type in database is nvarchar try it by modifying the following statement in your code
string query = "select * from my_table WHERE employeeName = '"+items+"'"
to
string query = "select * from my_table WHERE employeeName = N'"+items.ToString()+"'"
Prefix 'N' is used for the value to compare from checked item

MySql database connection syncing with C# to view specific table values

I'm implementing an application on C# connected to a MySql database. Part of the application I'm showing data from MySql database table1 in a multi-line textbox in every 2 minutes, using a timer. Right now, the code is running perfectly. But, in the textbox1 which I'm using to show database table1 row values, It's just clearing the retrieved data and get whole bunch of data from the table and shows in the textbox view. The problem is when the database gets larger (like thousands of rows) it'll clear and retrieve all the row data over and over again in every 2 minutes.
private void timer1_Tick(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
textBox1.Text = string.Empty; //Clearing the retrieved data
//looping and gets every row value from table1
while (myReader.Read())
{
if (textBox1.Text.Length > 0)
textBox1.Text += Environment.NewLine;
for (int i = 0; i < myReader.FieldCount; i++)
textBox1.Text += myReader[i].ToString() + " ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
}
There are two problems that I'm still struggling with:
01.) I want to get only the updated value from the data base.
02.) How to stick to the bottom in the multi-line text box when it keep updating?
Any help on this would be great.
Thanks in Advanced!
A posible solution for 01) is:
1) Store in a variable the last row id retrieved from table. (lastStoredID)
2) Change
command.CommandText = "Select * FROM database_name.table1";
to
command.CommandText = "Select * FROM database_name.table1 where id > " + lastStoredID ;
3) Remove line
textBox1.Text = string.Empty; //Clearing the retrieved data
Update:
If he wants only new inserted rows the solution above may be the right one.
If he wants not only just inserted rows, but updated rows the solution above is not the right one.

Passing C# String as SQL parameter for SELECT WHERE IN

I am writing a function to take as many multiple selected items from a Listbox and pass the vaules to a SQL Query to INSERT values into a table after selecting the filtered values from another table. The code I have typed is below and it doesn't seem to work (the problem is with the way I'm passing the string to the query.
string lbSites = "";
protected void Button1_Click1(object sender, EventArgs e)
{
string cns = "server=abc;database=testDB;Trusted_Connection=True";
using (SqlConnection con = new SqlConnection(cns))
{
using (SqlCommand command = con.CreateCommand())
{
command.CommandText = "INSERT INTO Activity (Hostname,Site,Status,System_Dept,Business_Dept)"
+ "SELECT * FROM Inventory WHERE Site IN ("+lbSites+");"
;
con.Open();
command.Parameters.AddWithValue("#lbSites", lbSites);
command.ExecuteNonQuery();
con.Close();
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
lbSites += "'" + ListBox1.Items[i].Value + "', ";
}
}
}
}
You should not directly pass values like this to SQL, as it leaves you open to a SQL Injection Attack.
Instead, you can figure out how many parameters you need, and then insert those parameter names into your query.
This approach will work for up to approximately 2,000 values (assuming SQL Server). If you need to pass more values, you will either need to break up the queries into sub-sets, or use parameter-value tables.
Example (not tested, so may have some bugs):
// Get your selected items:
var items = ListBox1.Items.Where(i=>i.Selected).Select(i=>i.Value).ToArray();
// Create a series of parameters #param0, #param1, #param2..N for each value.
string paramNames = string.Join(", ", Enumerable.Range(0,items.Count()).Select(e=>"#param"+e));
// Build the command text and insert the parameter names.
string commandText = "INSERT INTO Activity (Hostname,Site,Status,System_Dept,Business_Dept)"
+ "SELECT * FROM Inventory WHERE Site IN ("+ paramNames +")";
command.CommandText = commandText;
// Now add your parameter values: this binds #param0..N to the values selected.
for(int param=0;param<items.Count();param++)
{
command.Parameters.AddWithValue("#param" + param, items[param]);
}
The value of lbSites is lost everytime you've posted back. Keep it in your ViewState.
Besides, you don't need command.Parameters.AddWithValue("#lbSites", lbSites); since there's no #lbSites parameter in your sql.
try this
SELECT M.REG_NO, T.TYPE_ID
FROM MAIN AS M
INNER JOIN CLASSIFICATION AS C
ON M.REG_NO = C.REG_NO
INNER JOIN TYPE AS T
ON T.TYPE_ID = C.TYPE_ID
WHERE (#Types) like .LIKE '%,' +T.TYPE_ID+ ',%'

Categories

Resources