select gridview row after search - c#

Form 1 and 2
how do i auto select after i click search from another form ?
iam using C#. the textbox below only for store(check) i want the form 1 with gridview is selected
my code below on form 2 :
private void simpleButton1_Click(object sender, EventArgs e)
{
cari();
}
public void cari()
{
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
ds.Tables.Clear();
command.Connection = myConnection;
command.CommandText = "select * from General.genre WHERE genre Like '%"+textEdit1.Text.ToString()+"%' or code like '%"+textEdit1.Text+"%'";
myConnection.Open();
var buka = command.ExecuteReader();
if (buka.Read())
{
textEdit2.Text = buka[1].ToString();
}
else
{
MessageBox.Show("type genre");
}
// MessageBox.Show("kebaca");
}
catch (System.Exception ex)
{
MessageBox.Show("error" + ex);
}
myConnection.Close();
}

dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}

Related

C# datagridview shound not change until there is a result

Recently i developed a search function, but i want when a user inputs something on the textbox the datagridview to not go blank but instead to show the data that it already has and when the result is found than only show the result. Because now when i type anything on the search textbox the dgv immediately goes blank.
Here is my code:
private void txtBarkod_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtBarkod.Text)) {
resetTxTboxes();
}
MySqlConnection connection = Connection.prevzemiKonekcija();
try {
connection.Open();
MySqlCommand command;
MySqlDataAdapter adapter;
DataTable tabela;
string query = "SELECT * FROM artikli WHERE barcode like '%" + txtBarkod.Text + "%'";
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
tabela = new DataTable();
adapter.Fill(tabela);
dataGridView1.DataSource = tabela;
if (txtBarkod.Text == "") {
ShowDgV();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
Reset/Rebind the datasource of your datagridview only if you found something in your db.
if(tabela.Rows.Count > 0)
{
dataGridView1.DataSource = tabela;
}

How can i delete data from a datagridview c#?

When i use the code below,it does delete a row from a datagridview but when i refresh the page it does not..
private void DeleteData_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Selected)
{
dataGridView1.Rows.RemoveAt(row.Index);
break;
}
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow delrow = dataGridView1.Rows[i];
if (delrow.Selected == true)
{
dataGridView1.Rows.RemoveAt(i);
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + (i++) + "";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
What should i use to delete row from both local database and datagridview?
i think the connection not be assigned to the command object.
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
also i preferred to use DataGridView.SelectedRows instead of looping all records in grid.
full code
private void DeleteData_Click(object sender, EventArgs e)
{
var rowsToDelete = dataGridView1.SelectedRows;
using (SqlConnection sqcon = new SqlConnection(#"MY CONNECTION STRING"))
{
SqlCommand Scmd = new SqlCommand();
Scmd.Connection = sqcon;
sqcon.Open(); //ADDED
foreach (DataGridViewRow row in rowsToDelete)
{
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID=" + row.Cells["Id"].Value.ToString() + "";
int count = Scmd.ExecuteNonQuery();
dataGridView1.Rows.Remove(row);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
sqcon.Close();
}
}
Try this,
Delete from database use the unique column or the Id column.
//Make datagridview cell[0] the unique column in your table.
try
{
Scmd.CommandText = "DELETE FROM Technican WHERE ID='" + datagridview.rows[i].cell[0].value + "'";
sqcon.Open(); //ADDED
int count = Scmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

Datagridview Column Index Returning 0 after Update

I Bind Data to a DataGridview using the following code
private void BindGrid()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM mytable", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
if (flag == false)
{
flag = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView1.Columns.Insert(4, uninstallButtonColumn);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
I Update the selected record by hooking to a button click event in the datagridview row like this
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex ==4)
{
button4.Enabled = false;
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable where name= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", orderId);
myReader = command.ExecuteReader();
while (myReader.Read())
{
textBox1.Text = myReader["name"].ToString();
textBox2.Text = myReader["age"].ToString();
textBox3.Text = myReader["phone"].ToString();
textBox4.Text = myReader["address"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
}
Now i update the values using the code below
private void button5_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE mytable SET name=#NewName,age=#NewAge,phone=#NewPhone,Address=#NewAddress" +
" WHERE name=#oldname", conn))
{
cmd.Parameters.AddWithValue("#NewName", textBox1.Text);
cmd.Parameters.AddWithValue("#NewAge", textBox2.Text);
cmd.Parameters.AddWithValue("#NewPhone", textBox3.Text);
cmd.Parameters.AddWithValue("#NewAddress", textBox4.Text);
cmd.Parameters.AddWithValue("#oldname", orderId);
try
{
int rows = cmd.ExecuteNonQuery();
MessageBox.Show("Updated Successfully");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
BindGrid();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
button4.Enabled=true;
}
But after i click the Update Button then click on the Button Column corresponding to a Row e.ColumnIndex always returns 0.
What im i doing wrong?
UPDATE :
Please see the screenshot
Rahul's Answer will work but looks like orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value; should be modifiled to get Cells[1].Value and not 0 as 0 is the button cell from 2nd time onwards. But for 1st time you need to use 0 as then button is at index 4. Try below changes.
As far as I understand, issue is after update, you call the BindGrid again and since flag is true it just sets the datasource again for the grid and not generating button again thus button gets moved to index 0 followed by the datatable columns.
Another way to solve is modify your code a bit like
dataGridView1.Columns.Insert(0, uninstallButtonColumn);
dataGridView1.Columns[0].DisplayIndex = 4;
And then in CellClick event check for e.ColumnIndex == 0. This help you in showing the button at the position you want and always the click work as the columnindex never changes.
you can check button index like below without comparing its index:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO - Button Clicked - Execute Code Here
}
}

DataSet not updated with new row inserted in C#

i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

GridView Editing ,Deleting ,Updating is not working?

im taking Some Invoice No form a table to a Dropdownlist, after select the invoice number i can take all products to the grid view, with additional , price and all,
my problem is i have to click two times to edit the row, but it is not updating, when click edit button in first row in first time , it is not working , but after click on next row,s edit button first row is enabling the edit textboxes, but not updating only empty data on the grid ...
Image
http://i.stack.imgur.com/X8W6Q.gif
in this part im taking the data to grid ..
DataTable DataTbt = new DataTable();
SqlCommand Command = new SqlCommand();
SqlDataAdapter DtaAdapter = new SqlDataAdapter();
protected void ddlInvoiceNumber_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GetReturnRecords("Invoice No", ddlInvoiceNumber.SelectedValue);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
DtaAdapter.Dispose();
Command.Dispose();
Connection.Close();
}
}
private void GetReturnRecords(string searchBy, string searchVal)
{
try
{
Command = new SqlCommand("SP_SearchPurchasesLines", Connection);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("#SearchBy", searchBy);
Command.Parameters.AddWithValue("#SearchVal", searchVal);
DtaAdapter.SelectCommand = Command;
DtaAdapter.Fill(DataTbt);
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
Command.Dispose();
Connection.Close();
}
}
data binding to the grid..
private void BindReturnGrid()
{
try
{
DtaAdapter = new SqlDataAdapter("SP_SearchPurchasesLines", Connection);
DtaAdapter.Fill(DataTbt);
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = null;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
DtaAdapter.Dispose();
Connection.Close();
}
}
editing updating deleting row from grid...
protected void GridViewPurchaseReturn_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridViewPurchaseReturn.EditIndex = -1;
BindReturnGrid();
}
protected void GridViewPurchaseReturn_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewPurchaseReturn.EditIndex = e.NewEditIndex;
BindReturnGrid();
}
I think you need to add the bind gridview method in inside of !ISPostbak on page load event .
see this code
page-load ()
{
if(!IsPostback)
{
BindReturnGrid();
}
}
You have to modify your GridViewPurchaseReturn_RowUpdating and GridViewPurchaseReturn_RowDeleting methods to update the change:
protected void GridViewPurchaseReturn_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Your code to delete the records in db
BindReturnGrid();
}
protected void GridViewPurchaseReturn_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Your code to update the records in db
GridViewPurchaseReturn.EditIndex = -1;
BindReturnGrid();
}
EDIT: After you dispose your command and closing the connection, I think your GridView DataSource should be null. To avoid this, I would change the code like this:
//DataTable DataTbt = new DataTable();
//SqlCommand Command = new SqlCommand();
//SqlDataAdapter DtaAdapter = new SqlDataAdapter();
protected void ddlInvoiceNumber_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GetReturnRecords("Invoice No", ddlInvoiceNumber.SelectedValue);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//DtaAdapter.Dispose();
//Command.Dispose();
//Connection.Close();
}
}
private void GetReturnRecords(string searchBy, string searchVal)
{
DataTable DataTbt = new DataTable();
SqlDataAdapter DtaAdapter = new SqlDataAdapter();
try
{
SqlCommand Command = new SqlCommand("SP_SearchPurchasesLines", Connection);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("#SearchBy", searchBy);
Command.Parameters.AddWithValue("#SearchVal", searchVal);
using (Connection)
{
Connection.Open();
DtaAdapter.SelectCommand = Command;
DtaAdapter.Fill(DataTbt);
}
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//Command.Dispose();
//Connection.Close();
}
}
private void BindReturnGrid()
{
try
{
DataTable DataTbt = new DataTable();
SqlDataAdapter DtaAdapter = new SqlDataAdapter("SP_SearchPurchasesLines", Connection);
using (Connection)
{
Connection.Open();
DtaAdapter.Fill(DataTbt);
}
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = null;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//DtaAdapter.Dispose();
//Connection.Close();
}
}

Categories