How to add user defined row into a datatable? - c#

I have datagridview which is filled with values from DB when button clicked.
All these happen based on a condition from radiobutton.
Now i need to add some extra row (default value) into the datatable, each time these conditions apply.
When button clicked and radiobutton condition apply,these codes will happen.
if (radioButton1.Checked == true)
{
string query = "SELECT type,priceS FROM service WHERE type='" + button5.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, con);
dt.SelectCommand = cmd;
}dt.Fill(tt);
dataGridView1.DataSource = tt;
The query will return
string =type and int=priceS
from DB, i just need add string "S" with the "type" value
For example: if type = Style then in the datatable it be should "Style(S)"
any help is appreciated.

Instead of using Datatables i solved it in the MySQL Query itself
Query="Select Concat(type,'S'),price from service"
This will add the string S with that of the type's value.

Related

Why foreach loop does not work with datagridview selected rows in C#?

I am new to c# and using windows forms.
The following code loops through all selected rows in datagridview and take variables from cell0 and 4 as condition to use in sql query.
I multi-select rows then use this code and when I check the result in sql table I find this code only consider the first selected row in datagridview and ignore the rest.
Anyone knows how can I fix it, or what I am doing wrong? please help , thank you
foreach (DataGridViewRow row in DGV.SelectedRows)
{
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
MyConnection.Open();
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyCommand.Connection = MyConnection;
MyCommand.Parameters.Add("#_Delivery_State", SqlDbType.NVarChar).Value = button7.Text;
MyCommand.Parameters.Add("#_OrderNumber", SqlDbType.Int).Value = OrderNumber;
MyCommand.Parameters.Add("#_OrderDateTime", SqlDbType.DateTime).Value = OrderDateTime;
MyCommand.ExecuteNonQuery();
MyCommand.Parameters.Clear();
MyConnection.Close();
}
I multi-select rows then use this code and when I check the result in
sql table I find this code only consider the first selected row in
datagridview and ignore the rest.
That's too normal because you use same row cell as DGV.SelectedRows[0] in every iteration, not the rows that you iterate.
Change your
OrderNumber = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
OrderDateTime = Convert.ToDateTime(DGV.SelectedRows[0].Cells[4].Value);
to
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
using(var MyConnection = new MySqlConnection(conString))
using(var MyCommand = MyConnection.CreateCommand())
{
MyCommand.CommandText = "UPDATE List_of_All_Orders set Delivery_State=#_Delivery_State WHERE Order_Number=#_OrderNumber and Date_Time_Ordered =#_OrderDateTime";
MyConnection.Open();
foreach (DataGridViewRow row in DGV.SelectedRows)
{
MyCommand.Parameters.Clear();
OrderNumber = Convert.ToInt32(row.Cells[0].Value);
OrderDateTime = Convert.ToDateTime(row.Cells[4].Value);
MyCommand.Parameters.AddWithValue("#_Delivery_State", button7.Text);
MyCommand.Parameters.AddWithValue("#_OrderNumber", OrderNumber);
MyCommand.Parameters.AddWithValue("#_OrderDateTime", OrderDateTime);
MyCommand.ExecuteNonQuery();
}
}
I used AddWithValue in my example but you don't use this method. Use Add method overload as you did with proper MySqlDbType, not SqlDbType.

Insert query where table name is textbox text

I have a problem in button1 click event of inserting data into a table which table name be determined by whatever text is in textbox1
Should mean something like that:
tablename = textbox1.text;
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (#itemserial, #itemname, #itemcount, #itemimage)";
Having a textbox containing the name of your table is challenging because you should add extra care in handling this value. You should implement some kind of checking on this textbox value. A possible solution is to check against your database schema if the table typed by your user really exists.
You don't tell us which database system are you using so I will show an example using Sql Server
string tableName = textbox1.text;
using(SqlConnection cnn = new SqlConnection(... connectionstring...))
{
cnn.Open();
DataTable dt = cnn.GetSchema("TABLES");
DataRow[] rows = dt.Select("TABLE_NAME = '" + tableName + "'");
if(rows.Length > 0)
{
// Now you are sure to have a valid table in your textbox
// and could use the input value without risking an Sql Injection
string sql = "INSERT INTO [" + tableName + "] ([itemserial]," +
"[itemname],[itemcount],[itemimage]) " +
"VALUES(#itemserial,#itemname,#itemcount,#itemimage)";
.... the remainder of your code that use the query above....
}
else
MessageBox.Show("Please enter a valid name for your table");
Extending this approach you could change your TextBox to a ComboBox with ComboBoxStyle set to DropDownList (to block typing) and fill the ComboBox with the names returned by the GetSchema call above....
tablename = textbox1.text;
sql = string.Format("INSERT INTO {0} ([itemserial],[itemname],[itemcount],[itemimage])VALUES(#itemserial,#itemname,#itemcount,#itemimage)", tablename);
Although I would strongly recommend against this as it allows people to enter whatever they want into that textbox. Something like:
Robert; DROP TABLE Students;--
Which is discussed in more detail here:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
Change your query like this
sql = "INSERT INTO "+tablename+" ([itemserial],[itemname],[itemcount],[itemimage]) VALUES (#itemserial,#itemname,#itemcount,#itemimage)";

Inserting a row in database from DataGridview and Textfield

My problem is, I want to save data in the database from DataGridview and a Textbox. Here's my sample code:
connect.ConnectionString = coo;
connect.Open();
string str = string.Concat("insert into Sales values('", (1st column item in the datagridview), "','", textBox2.Text, "','", textBox3.Text, "','", textBox4.Text, "');");
command = new OleDbCommand(str, connect);
command.ExecuteNonQuery();
command.Connection = connect;
connect.Close();
Please provide guidance.
Inserting datGridView all rows to database:
We know to inserting values from textboxes and other data entry controls to database
but the values enter from dataGridView to database is little different than those ways
because here we have to insert all the rows which contains in dataGridView to database.
Click here for inserting values from textboxes to the datagridview control.So for the we
have to run a loop to to collect all the data from the all the rows from the database.
Event : The event to raise this code is saveButton_Click
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\naresh\My stuff\Thal tre tsks trim\Thalassemia\Data\thalsemia.accdb");
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
OleDbCommand cmd= new OleDbCommand("INSERT INTO table1(name,number,salory,) VALUES
('"+dataGridView1.Rows[i].Cells["Column1"].Value+"','"+dataGridView1.Rows[i].Cells["Column2"].Value+"',
'"+dataGridView1.Rows[i].Cells["Column3"].Value+" ' ",con);
cmd.ExecuteNonQuery();
}
con.Close();
I hope this code will help you.
to get the selected cell value you can use:
string Selection;
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
Selection=row.Cells[0].Value.ToString();
}
to add them in your query use parameters:
string query = "insert into Sales values(#param1,#param2,#param3,#param4)");
command = new OleDbCommand(query, connect);
command.Parameters.AddWithValue("#param1", Selection);
command.Parameters.AddWithValue("#param2", textBox2.Text);
command.Parameters.AddWithValue("#param3", textBox3.Text);
command.Parameters.AddWithValue("#param4", textBox4.Text);
command.ExecuteNonQuery();
command.Connection = connect;
connect.Close();
I will give you some guidelines how to do it but not provide your complete code:
You need a new column in your gridview and put a button/linkbutton in it as 'Edit/Save/Store' or whatever you want.
When user clicks that button, then ItemCommand Event of Gridview should be fired where you have to get the index of the selected row something like e.Rowindex (You can check the google for detailed tutorial on this) and once you have the index, that is the idea you need. In that event, you should save this data in the database.

C# DatagridVIew Delete SQL date

How i make delete a data SELECTED(CHECKED) from MYSQL in datagridview in C# ?
My code:
string CONFIG = "server=localhost;userid=root;password=admin;database=program";
MySqlConnection cone = new MySqlConnection(CONFIG);
MySqlCommand query2 = new MySqlCommand();
query2.Connection = cone;
query2.CommandText = "DELETE FROM TABLE WHERE ID = #ID";
// I believe the key from this problem stay in line below//
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRows);
cone.Open();
query2.ExecuteNonQuery();
cone.Close();
SelectedRow property of the gridview gives the entire row . So you need to provide the column value (in you case it is ID) -
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRow
.Cells[indexofIDcolumn].Value)

GridView on update check if a value from a cell is equal to something then insert values into database

I have a gridview and on row update I want to check if the value from
a cell is equal to something
The code was compiled I made a test to check if it works and it's not adding the values to the database , but if I delete the condition of checking if it's equal to smth . it works , it's adding the values from a ROW into the database.
GridViewRow row = GridView1.Rows[e.RowIndex];
string conn = "connection string";
string str = ((TextBox)(row.Cells[2].Controls[0])).Text;
string sqlquerry = "INSERT INTO table (Column1,Column2";
sqlquerry += " VALUES (#V,#V2)";
if(str == "Hi"){
using (SqlConnection conn = new SqlConnection(string))
{
using (SqlCommand cmmd = new SqlCommand(sqlquerry, conn))
{
cmmd.Parameters.AddWithValue("V", e.OldValues[0].ToString());
cmmd.Parameters.AddWithValue("V2", e.NewValues[1].ToString());
Conectare.Open();
cmmd.ExecuteReader();
}
}
}
as it is a insert query you should use
'cmd.ExecuteNonQuery' and then compare the string with equals method.

Categories

Resources