Add row from datagridview1 to datagridview2 - c#

I have two datagridviews in one from. I need to get data from database to datagridview1 (using Select *from database...) then I want to add data from datagriwview to datagridview2 using Selected Rows.
First I wanted to solve this problem to get Selected Row's ID, when I select row in datagridview it shows in datagridview2, but when I select another row, it is updating in datagridview, it does not add as new row. I tried several ways but did not solve this problem, Is there anyone help me to solve this problem? Thanks
private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32
(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells["id"].Value);//3
try
{
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
dataGridView2.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Is quite simple the explanation: everytime that you make a double click to a datagridview1's cell you replace the old datatable with a new one. If you want append the result you can do something like this:
MySqlConnection conn = new MySqlConnection(connection);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + id.ToString() + "'";
conn.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if(dataGridView2.DataSource != null) {
DataTable pr = dataGridView2.DataSource as DataTable;
pr.Merge(dt);
dataGridView2.DataSource = pr;
}
else
dataGridView2.DataSource = dt;

Since you have all information in datagridview1 you should just copy the contents of the selected row into a new row for datagridrow2.
The DataGridView is based on a DataSet which contains DataTables.
The DataTable contains rows.
You cannot move a row from one table to annother.
Instead you have to create a new row and insert into the DataTable of DataGridView2

private void dataGridView1_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow.Cells["Id"].Value != null)
{
int Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["Id"].Value);
MySqlConnection start = new MySqlConnection(baglanti);
MySqlCommand command = start.CreateCommand();
command.CommandText = "SELECT id, muayine_adi, sabit_qiymet FROM tibbi_xidmetler WHERE id = '" + Id + "'";
start.Open();
MySqlDataAdapter oxu = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
oxu.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
int idx = dataGridView2.Rows.Count - 1;
dataGridView2.Rows.Add(dt.Rows.Count);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int rVal = (idx + i) + 1;
dataGridView2.Rows[rVal].Cells["id"].Value = dt.Rows[i]["id"].ToString();
dataGridView2.Rows[rVal].Cells["muayine_adi"].Value = dt.Rows[i]["muayine_adi"].ToString();
dataGridView2.Rows[rVal].Cells["sabit_qiymet"].Value = dt.Rows[i]["sabit_qiymet"].ToString();
}
}
start.Close();
}
}

Related

How to add button in each row of a grid view in asp.net for shopping cart.The button should delete the row

public void viewitemincart()
{
decimal total = 0;
int rowIndex = 0;
if (Session["Cart"] != null)
{
List<OrderDetail> otherorders = (List<OrderDetail>)Session["Cart"];
DataSet ds = new DataSet();
foreach (OrderDetail order in otherorders)
{
using (SqlConnection connection = new SqlConnection(DatabaseConnection.GetConnectionString()))
{
connection.Open();
string sql = "select "+ rowIndex+1 + " as no,itemName as Item, " + order.Quantity + " as Quantity, Price, " + order.Quantity + "*price as Total from tbl_item where itemId=" + order.ProductId;
SqlCommand sqlcmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
da.Fill(ds);
total += Convert.ToDecimal(ds.Tables[0].Rows[rowIndex]["Total"]);
rowIndex += 1;
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
lblGrand.Visible = true;
lblGrandTotal.Visible = true;
lblGrandTotal.Text = total.ToString();
}
}
//The code binds data in session["cart"] to Grid View.
//The code is used to add item in cart session and have it displayed in grid view.
//Now, i want to add a delete button on each row of the session and upon clicking the delete button the respective row needs to be deleted from the session.

How to edit data in search result in c#

I managed to create a code for my edit button and search button. My edit button is functional. It can edit my data in database, my search code is also functional. My problem is to edit data in search results. Like if i search "naruto", my datagridview will filter all the names that has "naruto" on the database. After i choose and doubleclick on the result, all data will reappear to my textbox. But when i edit that data, it doesn't work. Instead, the first data on my database is the one that is changing not the one that i choose. My edit code is working if i don't search any names and don't choose on the search result.
here's my codes. Please HELP...
private void JOGridView_DoubleClick(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from JobOrder", con);
if (JOGridView.CurrentCell != null && JOGridView.CurrentCell.Value != null)
{
TBName.Text = JOGridView.SelectedRows[0].Cells[0].Value.ToString();
TBContact.Text = JOGridView.SelectedRows[0].Cells[1].Value.ToString();
CBStatus.Text = JOGridView.SelectedRows[0].Cells[2].Value.ToString();
TBModel.Text = JOGridView.SelectedRows[0].Cells[3].Value.ToString();
TBSerial.Text = JOGridView.SelectedRows[0].Cells[4].Value.ToString();
TBAccess.Text = JOGridView.SelectedRows[0].Cells[5].Value.ToString();
TBRB.Text = JOGridView.SelectedRows[0].Cells[6].Value.ToString();
TBRP.Text = JOGridView.SelectedRows[0].Cells[8].Value.ToString();
TBIT.Text = JOGridView.SelectedRows[0].Cells[10].Value.ToString();
CBRamarks.Text = JOGridView.SelectedRows[0].Cells[11].Value.ToString();
TBCharge.Text = JOGridView.SelectedRows[0].Cells[12].Value.ToString();
TBRELB.Text = JOGridView.SelectedRows[0].Cells[13].Value.ToString();
}
}
private void BTNEdit_Click(object sender, EventArgs e)
{
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to Edit this record?", "Update Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM JobOrder", con);
da.Fill(dt);
dt.Rows[JOGridView.CurrentRow.Index].BeginEdit();
dt.Rows[JOGridView.CurrentRow.Index][1] = TBName.Text;
dt.Rows[JOGridView.CurrentRow.Index][2] = TBContact.Text;
dt.Rows[JOGridView.CurrentRow.Index][3] = CBStatus.Text;
dt.Rows[JOGridView.CurrentRow.Index][4] = TBModel.Text;
dt.Rows[JOGridView.CurrentRow.Index][5] = TBSerial.Text;
dt.Rows[JOGridView.CurrentRow.Index][6] = TBAccess.Text;
dt.Rows[JOGridView.CurrentRow.Index][7] = TBRB.Text;
dt.Rows[JOGridView.CurrentRow.Index][8] = DTDR.Text;
dt.Rows[JOGridView.CurrentRow.Index][9] = TBRP.Text;
dt.Rows[JOGridView.CurrentRow.Index][10] = DTDF.Text;
dt.Rows[JOGridView.CurrentRow.Index][11] = TBIT.Text;
dt.Rows[JOGridView.CurrentRow.Index][12] = CBRamarks.Text;
dt.Rows[JOGridView.CurrentRow.Index][13] = TBCharge.Text;
dt.Rows[JOGridView.CurrentRow.Index][14] = TBRELB.Text;
dt.Rows[JOGridView.CurrentRow.Index][15] = DTDR.Text;
dt.Rows[JOGridView.CurrentRow.Index].EndEdit();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Update(dt);
displayrecords();
MessageBox.Show("Selected record has been Updated!", "Done Updating ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
clearrecords();
}
}
private void TBSearch_KeyUp(object sender, KeyEventArgs e)
{
if (TBSearch.Text == " ")
{
}
else
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from JobOrder where Name like ('" + TBSearch.Text + "%')";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JOGridView.DataSource = dt;
con.Close();
}
It's hard to be more specific without seeing more of your code, but the core problem is at least in part that you're not using an MVVM (model view viewmodel) or MVC style binding between the query results and the database query.
Here's why you're only updating the first row in the table rather than the selected row
//creates a new table not visible or linked anywhere
DataTable dt = new DataTable();
//gets every record in JobOrder
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM JobOrder", con);
//fills the DataTable dt with all records from JobOrder
da.Fill(dt);
//uses the current index from the items in JOGridView to select a row in the unconnected/unrelated DataTable dt
dt.Rows[JOGridView.CurrentRow.Index].BeginEdit();
dt.Rows[JOGridView.CurrentRow.Index][1] = TBName.Text;
If you want it to work as written, you'll need to use some value from JOGridView.CurrentRow and match it to a row in dt. Then you can build your update query aimed at the correct row.
Ideally instead, you'll re-write the application to use a proper MVVM style binding to do all of the connections for you automatically.

How to print selected row from DataGridView in C# with SQL

Using the following code the first row in SQL is printed only, How can I print selected row from DataGridView in C# with SQL:
public partial class PrintScreen : Form
{
SqlConnection con = new SqlConnection(#"Server = TEST;DataBase=Registration;Integrated Security=true;");
SqlDataAdapter da;
DataTable dt = new DataTable();
public PrintScreen()
{
InitializeComponent();
da = new SqlDataAdapter("select * from data_graduation", con);
da.Fill(dt);
this.dataGridView1.DataSource = dt;
}
private void Print_ys_ar_cert_Click(object sender, EventArgs e)
{
Print_ys_ar_cert frm = new Print_ys_ar_cert();
da = new SqlDataAdapter("select * from data_graduation where ID_gra = '" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'", con);
da.Fill(frm.RegistrationDataSet1.data_graduation);
frm.reportViewer2.RefreshReport();
frm.Show();
}
}
Currently you are passing value of Cells[0] of first row of the grid, you need to pass value of selected row:
if(dataGridView1.SelectedRows.Count>0)
{
var selectedValue = dataGridView1.SelectedRows[0].Cells[0].ToString();
//rest of code
}
Since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report this way:
var row = ((DataRowView)(dataGridView1.SelectedRows[0].DataBoundItem)).Row;
frm.RegistrationDataSet1.data_graduation.Rows.Add(row.ItemArray);
//rest of code

Display selected columns vertically

I have a table named orders.
I want to display Order Date, Sum of the product quantity ordered and the product_name.
Here is the data I want to display:
Data to Display
As above, I want product names to be displayed horizontally, with the sum of the product orders displayed vertically by date.
I am using C# and an MS Access database.
I am able to display the data in gridview row-wise. Here is the code:
private void btn_all_orders_Click(object sender, EventArgs e)
{
try
{
connection.open
OleDbCommand command = new OleDbcommand();
command.connection = connection;
string query = "select order_date as 'Order Date', product_name as
'Items', Sum(order_quantity) as 'No of Orders' from order where cust_id =
'" + txt_cust_id.Text + "' group by order_date, product_name";
command.commandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;
connectionn.Close();
}
catch (Exception ex)
{
Messagebox.Show("Error " + ex);
connection.Close();
}
}
How do I change this to achieve the goal described above?
I think you are asking for is this:
What you will need to do is ADD a Column to your to your datatable.
Then add an expression to that column it.
da.Fill(dt);
dt.Columns.Add("TOTAL");
dt.Columns("Total").Expression = "Count(Product1) + Count(Product2) + Count(Product3)";
datagridview.DataSource = dt;
connectionn.Close();
The totals on the bottom are coming from your SelectQuery => Sum(order_quantity). You can modify the query to get rid of that.
Some info
Of course the query could be changed so that it returns a computed column back and then you do not need to do it in the datatable.
Actual SQL for changing the query so that it returns a computed column back - https://stackoverflow.com/questions/3932205/to-calculate-sum-two-alias-named-columns-in-sql
The code above is pseudo - untested code - so please read the links.
EDIT
You could also look here : Display Data Vertically in the DataGridview
Too much code to post but basically the real work is done by flipping the dataset - as Mr. Gamal did.
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{ table.Columns.Add(Convert.ToString(i)); }
DataRow r;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
{ r[j] = dt.Rows[j - 1][k]; }
table.Rows.Add(r);
}
ds.Tables.Add(table);
}
return ds;
}

Adding datarows to datagrid from database

I'm new to databases. I'm trying to make a search utility to match user input string with records in database and display them.
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;
DataSet ds1;
private void Form1_Load(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
ds1 = new DataSet();
con.ConnectionString = "";
con.Open();
string sql = "SELECT * From tblLecturers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(ds1, "Lecturers");
con.Close();
}
Form2 secondForm = new Form2();
private void btnFind_Click(object sender, EventArgs e)
{
this.Hide();
secondForm.Show();
string searchFor = textBox1.Text;
int results = 0;
int i;
DataRow[] returnedRows;
if (radioButton1.Checked)
{
returnedRows = ds1.Tables["Lecturers"].Select("Name like '%" + searchFor + "%'");
}
else
{
returnedRows = ds1.Tables["Lecturers"].Select("Department like '%" + searchFor + "%'");
}
results = returnedRows.Length;
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
}
else
{
MessageBox.Show("No such Record");
}
}
There's no error but it's just displaying a blank grid. returnedRows contains all the rows whose contents match the user input. I'm pretty sure this isn't though:
secondForm.dataGridView1.DataSource = returnedRows;
Tried rows.add using for loop, won't work. How do i do this?
Thanks in advance.
Call the BindMethod of gridView
if (results > 0)
{
secondForm.dataGridView1.DataSource = returnedRows;
secondForm.dataGridView1.DataBind();
}
else
{
MessageBox.Show("No such Record");
}
Ignore DataBind method, there is no method for windows GridView.
The datarow array can be added to dataset or datatable, using the dataset or datatable we can directly bind the GridView

Categories

Resources