Reload Items of dataGridView - c#

I have a dataGridView in C# WinForms that display a custom items from a table in my database, and I have textbox and button for insert new rows in that table.
When I click on button, the Text of textbox will be inserted into table, I want after inserting, dataGridview can reload new item and display it too.
I use dataGridView1.Update(); and dataGridView1.Refresh(); and don't work.
I know that dataGridView can insert new items, but I want to insert items in my way.
it's my code on click event:
private void button1_Click(object sender, EventArgs e)
{
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
MessageBox.Show("Error");
conn.Close();
}

You should try databinding, and possibly populate your data into ObservableCollection, you don't need manually call update, all is done automatically.
See also this post: Reloading Listbox content

Well you will have to use DataBind method to reload the datagridview.
Lets say DataGridView1 is the ID of your datagridview then use the below line of code after your Insert statement.
DataGridView1.DataSource = yourDataSource;
Refresh and Update methods wont server your purpose here.
All read this link for more information.
Can you alter your code to this:
private void button1_Click(object sender, EventArgs e)
{
int rowsAffected = 0;
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
if (rowsAffected > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
{
MessageBox.Show("Error");
}
}

this.marjaTableAdapter.FillBy(this.bankDataSet10.marja);
it's my answer

Related

I want to insert data into a table

I'm building a C# Windows Forms database application. Data should be written in a text field and saved in a table using a button. My problem is that the data is not saved in the table.
I have built a list that should show the records of the table. When you click on the insert button, the text is displayed in the list, but it is not saved in the table.
My code:
private void insert_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tab_Musik values (#Titel,#Inerpret,#Genre)", con);
cmd.Parameters.AddWithValue("#Titel", int.Parse(txt_Titel.Text));
cmd.Parameters.AddWithValue("#Inerpret", txt_Interpret.Text);
cmd.Parameters.AddWithValue("#Genre", double.Parse(kmb_Genre.Text));
cmd.ExecuteNonQuery();
con.Close();
}
private void show[enter image description here][1]_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tab_Musik", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
For the problem you described about clicking the insert button, the data cannot be saved to the table, you can try the following code:
private void btnAdd_Click(object sender, EventArgs e)
{
string con_string = "database connection string";
SqlConnection sqlConnection = new SqlConnection(con_string);
string myinsert = "insert into tab_Musik values (#Titel,#Inerpret)";
SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);
mycom.Parameters.AddWithValue("#Titel", textBox1.Text);
mycom.Parameters.AddWithValue("#Inerpret", textBox2.Text);
sqlConnection.Open();
mycom.ExecuteNonQuery();
mycom.Clone();
mycom.Dispose();}
Show results:

How To delete from both database and datagridview

So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}

How can I delete a row in a datagrid view and update the MySQL database on a delete button click event?

So far I have managed to delete the record from the datagrid view on a button click event, but the problem is that the database is not changing.
I'm using datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex); to remove the row from the datagrid and cmd = new MySqlCommand("DELETE FROMsarasavi_library.book_titleWHEREbook_number= 'book_number';"); to remove it from the database.
Below is my full code for the delete button click event:
private void btn_delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in datagrid_booktitles.SelectedCells)
{
if (oneCell.Selected)
datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
cmd = new MySqlCommand("DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`= 'book_number';");
}
}
Am I doing something wrong here? I have a feeling that there's a problem with my MySQL command, But I can't think of another way. Any ideas?
Try This for delete selected row of datagridview from database.
SqlConnection con=new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=DatabaseName;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM table_Name WHERE Column_Name=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
con.Open();
delcmd.Connection = con;
delcmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("Row has been Deleted");
}
You need create and provide instance of MySqlConnection for executing commands on database.
private void btn_delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in datagrid_booktitles.SelectedCells)
{
if (oneCell.Selected == false) continue;
datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
string query =
"DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`='book_number'"
using(var conn = new MySqlConnection("yourConnectionString"))
{
using(var command = new MySqlCommand(query, conn))
{
conn.Open();
command.ExecuteNonQuery();
}
}
}
}
Think I found the answer for this. I have assigned the datagrid value to a string and used it in the database query.
foreach (DataGridViewCell oneCell in datagrid_booktitles.SelectedCells)
{
if (oneCell.Selected == false) continue;
string i = datagrid_booktitles.SelectedRows[0].Cells[1].Value.ToString();
datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
string query = "DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`='" + i +"'";
using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ToString()))
{
using (var cmd = new MySqlCommand(query, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
}

filter a listbox bound to a acces database using a textbox

I'm pretty new in c#, taking lessons but with what i'm trying to do i know that i'm way ahead of schedule.
I have a form with a listbox and a textbox.
this is how I populate the listbox
private void Centrale_Gegevens_Load(object sender, EventArgs e)
try
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand combo = new OleDbCommand();
combo.Connection = verbinding;
string query = "select NaamPatient from tbl_Patient";
combo.CommandText = query;
OleDbDataReader reader = combo.ExecuteReader();
while (reader.Read())
{
lstBox.Items.Add(reader["NaamPatient"]);
}
verbinding.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
the listbox is in that way populated with names of persons.
The textbox named textbox1 is what i want to use to filter the listbox.
This is what i got sofare, but it doesn't work.
private void textBox1_TextChanged(object sender, EventArgs e)
{
OleDbConnection verbinding = new OleDbConnection();
verbinding.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\Het Vlaamse Kruis\Het Vlaamse Kruis\data\Patienten.accdb; Jet OLEDB:Database Password=internet;";
verbinding.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_Patienten where NaamPatient like '" + textBox1.Text + "%' ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
lstBox.DataSource = dt;
lstBox.DisplayMember = "NaamPatient";
verbinding.Close();
}
I have red almost everything I can find on the net about it, bus no mather what i do, I can't get it to work.
How can I get if I type A in the textbox that the listbox shows all the names beginning with A, And if I type AB that the listbox shows everything beginning with AB etc.
Thanks in advance
Firstly, in Centrale_Gegevens_Load, table's name is tbl_Patient but in textBox1_TextChanged, it is tbl_Patienten.
Secondly,Connection property has not been initialized.
you must insert this: cmd.Connection = verbinding; after initializing the cmd;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = verbinding;
Sorry for my bad English.

All Row has a Delete Button in Gridview

I have a simple page like this. (EKLE = ADD, SİL = DELETE)
And my AVUKAT Table like this.
Simplify, When i choose first dropdown MUSTERI and second dropdown AVUKAT , add the database (getting HESAP (number) automaticly) or delete the database and gridview.
This is my code.
ADD Click
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/*GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
DELETE Click
protected void Delete_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("DELETE FROM AVUKAT WHERE MUSTERI = #MUSTERI AND AVUKAT = #AVUKAT AND HESAP = #HESAP", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/* GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
My manager wants, delete process is so hard. Let's make easy. Because when i want to delete some data, i must choose two dropdownlist and then delete(Sil) button.
We should prefer that every row has a delete button. Then when we click the button. Then must be deleted gridview AND databse.
I found perfect example on the internet abuot what i want.
I think if we can do that, Sil(Delete) Button should be deleted.
How can we do that?
I think AutoDeleteButton don't work like this. Right? It just deleted from Gridview. Not Database. But i want deleting both (Gridview AND Database)
You need to ensure you calling the correct method.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events.aspx
Clicking the button will run the "RowDeleting" method then "RowDeleted".
Edit - forgot to mention, once you've run your deleted method you'll need to rebind the gridview.
GridView1.DataBind()

Categories