I have a existing datagridview and a search textbox.
When I type a search text and click on the search button based on the below method (using stored procedures), I like to have it auto reload the datagridview with the search results.
How can I achieve this?
public static void searchAny(String searchFields, String tblName, String connectionString, SqlCommand tblscmd, SqlDataAdapter tbldataadaptor, DataTable tbldatatable, SqlCommandBuilder cmbuilder, DataGridView DataGridViewName)
{
using (SqlConnection tblconn = new SqlConnection(connectionString))
{
tblconn.Open();
SqlCommand tblcmd = new SqlCommand();
tblcmd.Connection = tblconn;
tblcmd.CommandType = CommandType.StoredProcedure;
tblcmd.CommandText = "usp_searchany";
tblcmd.Parameters.Add("#stringToFind", SqlDbType.NVarChar);
tblcmd.Parameters["#stringToFind"].Value = "%" + searchFields + "%";
tblcmd.Parameters.Add("#table", SqlDbType.NVarChar);
tblcmd.Parameters["#table"].Value = tblName;
cmbuilder.DataAdapter = tbldataadaptor;
tbldatatable.DefaultView.AllowDelete = true;
tbldatatable.DefaultView.AllowEdit = true;
tbldataadaptor.Fill(tbldatatable);
DataGridViewName.ReadOnly = false;
DataGridViewName.DataSource = tbldatatable;
tblconn.Close();
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
tbldatatable.Clear();
String searchFields = SearchTextBox.Text;
GeneralMethods.searchAny(searchFields, "tblClients", connectionString, tblcmd, tbldataadaptor, tbldatatable, cmbuilder, dataGridView);
dataGridView.DataSource = tbldatatable;
dataGridView.Refresh();
}
You have to filter your DataGridView's DataSource...like the following way...It's not required to clear,bind or refresh the datagridview...
From the CellEndEidt this is possible....
Simply you can filter the DataGridView's DataSource
private void MyDataGrid1_CellEndEdit(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
if (e.RowIndex == 0)
{
if (myDataGrid1.CurrentCell.Value.ToString().Trim().Length > 0)
{
MyFilterString="Field1=Feild2 and Field3>Field4";
}
MyDtb1.DefaultView.RowFilter = FilterString;
}
}
Related
I'm trying to add some data from a SQLite database, inside a ListView.
I'm having some difficulties as I want to insert all the data of the column and not a single record.
TEST CODE:
Form1.cs {Load}
private void home_form_Load(object sender, EventArgs e)
{
listView1.Refresh();
listView1.View = View.Details;
listView1.Columns.Add("ID");
listView1.Columns.Add("Grado");
listView1.Columns.Add("Cognome");
listView1.Columns.Add("Nome");
listView1.Columns.Add("Status");
}
Form1.cs {menu_button_gestionepax}
private void menu_button_gestionepax_Click(object sender, EventArgs e)
{
menu_button_dashboard.BackColor = System.Drawing.Color.DeepSkyBlue;
panel_dashboard.Visible = false;
gestionepersonale_panel.Visible = true;
menu_button_gestionepax.BackColor = System.Drawing.Color.Blue;
listView1.Refresh();
ListViewItem lst = new ListViewItem();
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
lst.SubItems.Add(LoadUsers.ManagerFind());
listView1.Items.Add(lst);
/*
string[] row = { LoadUsers.ManagerFindid(), LoadUsers.ManagerFindid() };
var listViewItem = new ListViewItem(row);
infobox_listview.Items.Add(listViewItem);
*/
}
LoadUsers.cs
public dynamic string ManagerFind()
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var select = cnn.Query($"select id from utenti");
if (select.Any())
{ return select[0].ToString(); }
else return "wrong";
}
}
I have also done various other tests and one of the difficulties in some cases is to call string ManagerFind() from LoadUsers.cs
Try something like this to get your rows and columns from your sql i know this is how you do it in SQL im sure there is a similar way to do it with sqlLite
using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
SqlCommand sqlCommand =
new SqlCommand(
"select id from utenti",
connection)
{
CommandType = CommandType.Text,
CommandTimeout = 20
};
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
string stringField = reader.GetFieldValue<string>(1);
}
}
reader.Close();
}
connection.Close();
}
I'm trying to insert data to a SQL Server with a dataGridView.
Here's what I have now in my buttonSave_Click :
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
For now this piece of code has a weird behavior because it throws an exception System.Data.SqlClient.SqlException : Must declare the scalar variable "#size" but what I wrote in the cells is still added to the database.
very likely command cannot be executed on last DataGridView row, which is reserved for new item input. and all previous items are inserted properly.
it happens because (row.Cells[0].Value != null && row.Cells[1].Value != null) check for that row returns false and parameters are not added. the next statement insert.ExecuteNonQuery(); tries to run a command without required parameters and fails
create and execute insert command only for valid rows:
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
insert.ExecuteNonQuery();
}
}
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand();
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert = ("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
The Error is occur as you are using the variable before declaring them. Please Declare them prior with value before using into the Query.
This should do what you want.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}
You can find LOTS of great examples from the link below.
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
This is my first question on this site so i apologise in advance if I format it incorrectly.
I am creating a system which should be able to search a database (dataGridView) using multiple checkboxes. I found some code online to search it using 3 checkboxes but am unsure how to extend this. I will need to be able to search using 50+ checkboxes. The following code is executed upon pressing of a search button which will display corresponding rows in my database. I want to know to most efficient way to extend this solution to 50+ checkboxes.
private void button1_Click(object sender, EventArgs e)
{
String filterdata = "";
if (checkBox1.Checked)
{
if (checkBox2.Checked || checkBox3.Checked)
{
filterdata = "'T05A1.1',";
}
else
{
filterdata = "'T05A1.1'";
}
}
if (checkBox2.Checked)
{
if (checkBox3.Checked)
{
filterdata = filterdata + "'C16D6.2',";
}
else
{
filterdata = filterdata + "'C16D6.2'";
}
}
if (checkBox3.Checked)
{
filterdata = filterdata + "'F41E7.3'";
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//cmd.CommandText = "Select * from Table1 where elegansgeneID ='" + filterdata + "'";
cmd.CommandText = "Select * from Table1 where elegansgeneID in(" + filterdata + ")";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Try this more shorter approach:
private void Button1_Click(object sender, EventArgs e)
{
var values = new List<string>();
if (checkBox1.Checked)
values.Add("'T05A1.1'");
if (checkBox2.Checked)
values.Add("'C16D6.2'");
if (checkBox3.Checked)
values.Add("'F41E7.3'");
// and so on
String filterdata = string.Join(",", values);
...
}
Alexander Petrov's answer is correct.
But if you are getting more than 50 Check boxes then I would suggest you use CheckBoxList. The code becomes more simpler then.
public Form1()
{
InitializeComponent();
List<string> filters = new List<string> { "T05A1.1", "C16D6.2", "F41E7.3" };
checkedListBox1.Items.Clear();
foreach (string filter in filters)
{
checkedListBox1.Items.Add(filter);
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> selectedFilter = new List<string>();
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
selectedFilter.Add("'" + checkedListBox1.CheckedItems[i].ToString() + "'");
}
string query = "Select * from Table1 where elegansgeneID in(" + string.Join(",", selectedFilter) + ")";
}
With CheckBoxList, you can just add your filters in the filters List variable and it will generate your list. This will keep your code short as well.
I am trying to make cascading combo boxes. When I select values in combo boxes for the first time everything is OK, but when I return to first combo box and change to some other value, new items in the other combos are appended to the old items. This is my code bellow:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
private void FillStreet(String IdCity)
{
//cityCombo.Items.Clear()
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}
Try this:
public Apartment()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(Connection.cnnDatabase1);
Database1DataSet ds = new Database1DataSet();
private void FillLocation()
{
//locationCombo.Items.Clear()
SqlDataAdapter daLocation= new SqlDataAdapter("select * from Location", con);
ds.Tables["Location"].Clear();
daLocation.Fill(ds, "Location");
con.Open();
locationCombo.ItemsSource = ds.Tables["Location"].DefaultView;
locationCombo.DisplayMemberPath = "Location";
locationCombo.SelectedValuePath = "IdLocation";
con.Close();
}
private void FillCity(String IdLocation)
{
/*cityCombo.Items.Clear() -- I have tried inserting this,
but I am getting an error "Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead." on that part
when I reselect the combo.*/
if(!String.IsNullOrWhiteSpace(IdLocation))
{
ds.Tables["City"].Clear();
SqlDataAdapter daCity= new SqlDataAdapter("select * from City where IdLocation= " + IdLocation, con);
daCity.Fill(ds, "City");
con.Open();
cityCombo.ItemsSource = ds.Tables["City"].DefaultView;
cityCombo.DisplayMemberPath = "City";
cityCombo.SelectedValuePath = "IdCity";
con.Close();
}
}
private void FillStreet(String IdCity)
{
if(!String.IsNullOrWhiteSpace(IdCity))
{
s.Tables["Street"].Clear();
SqlDataAdapter daStreet= new SqlDataAdapter("select * from Street where IdCity= " + IdCity, con);
daStreet.Fill(ds, "Street");
con.Open();
cityCombo.ItemsSource = ds.Tables["Street"].DefaultView;
cityCombo.DisplayMemberPath = "Street";
cityCombo.SelectedValuePath = "IdStreet";
con.Close();
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
FillLocation();
}
private void locationCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(locationCombo.SelectedValue != null)
{
String idLocation= locationCombo.SelectedValue.ToString();
FillCity(idLocation);
}
}
private void cityCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(cityCombo.SelectedValue != null)
{
String idCity = cityCombo.SelectedValue.ToString();
FillStreet(idCity);
}
}
Since cityCombo.Items.Clear() is not an option in this case as mentioned in the code comments, you can clear the datatable instead:
ds.Tables["City"].Clear();
And in order to avoid the NullReferenceException in cityCombo_SelectionChanged you can check the cityCombo.SelectedValue for null.
You are reusing the DataSet everywhere. So it will keep appending. As I said in the comments, either clear the DataSet or make a local one to each function.
I have three combo-box which filtering value in different tables. For the first two combo-box i have no problem but for the third combo-box, I got error show input strings was not in correct format. I using the same code for the other two and it working correctly. Can someone specify how to troubleshoot this problem?
Here my code:-
This one is for combobox two which worked perfectly:-
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
This is the code which show error
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedValue.ToString() != null)
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
I hope someone can show me how to rectify this problem. Thanks.
***UPDATE****
Here the full code
private void FillPier(int BridgeID)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, PierName, BridgeID FROM tbPier WHERE BridgeID = #BridgeID";
cmd.Parameters.AddWithValue("#BridgeID", BridgeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbPier.DataSource = objDs.Tables[0];
cbPier.DisplayMember = "PierName";
cbPier.ValueMember = "PierID";
}
}
private void FillDataPoint(int PierDP)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, InspectDate FROM tbDatapoint WHERE PierID = #PierID";
cmd.Parameters.AddWithValue("#PierID", PierDP);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbInspect.DataSource = objDs.Tables[0];
cbInspect.DisplayMember = "InspectDate";
cbInspect.ValueMember = "PierID";
}
}
private void ViewBridge_Load(object sender, EventArgs e)
{
FillBridge();
}
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedIndex != 1)
{
int PierDP = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierDP);
}
}
Check if this can be converted to int first like this:
int x = 0
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (Int32.TryParse(cbPier.SelectedValue.ToString(), out x))
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
Or using the SelectedIndex property:
if(cbPier.SelectedIndex != -1)
{
.....
}
What are the cbPier.DisplayMember and cbPier.ValueMember ? Is the diplay member the string and value member the int? Double check if that's the case first ...