Display tables from SQL in DataGridView - c#

I created a DataBase named charityah containing 5 tables. Their names are listed in a combobox.
When I choose one of them I want to display their content in a DataGridView.
What I tried is: first I linked the DataGridView to this database and tried this code that I found:
SqlConnection connection = new SqlConnection();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = comboBox1.Text;
connection.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Downloads\charityah.mdf;Integrated Security=True";
using (connection)
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from "+s, connection);
DataSet ds = new DataSet();
adapter.Fill(ds, s);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Refresh();
}
}
This method doesn't give me any errors and it finds the tables, but nothing is seen in the DataGridView.

Since you report (comments) that there are rows, it sounds like the primary problem (connection disposal aside) is an issue with data-binding. A few thoughts leap to mind:
is the table in virtual mode?
is it adding columns?
do the columns already exist?
You might want to try adding:
dataGridView1.VirtualMode = false;
dataGridView1.Columns.Clear();
dataGridView1.AutoGenerateColumns = true;
before the:
dataGridView1.DataSource = ds.Tables[0];
You might also want to check that dataGridView1.DataMember doesn't have a value assigned.

try this, some times nonsense items do create a lot of mess. so try setting autogenerate columns to true. may this starts showing you the results. because as per your comments, it dosent seems there could be any other issue. so just give it a try
dataGridView1.AutoGenerateColumns = true;

Related

Changes to DataGridView aren't being reflected in database

I have a DataGridView control and a save button. When the Save button is clicked, I want any changes made to the DataGridView to be reflected in my database via a DataAdapter Update() command. However, after hitting the save button and reloading the form, the updates are not there.
Here is all the code for the Save button currently:
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
con.Open();
SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
myBuilder.GetUpdateCommand();
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
con.Close();
}
EDIT: I had forgotten to set the datasource of my DGV to the datatable. Here's the working code:
private void btnSave_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
dgvProductInfo.DataSource = dt;
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
dt.Clear();
adapter.Fill(dt);
}
}
Your code has several problems:
You are not enclosing the SQLConnection in a using statement. You should always use this pattern so that the connection is properly disposed: using(var connection = new SqlConnection(...)){ rest of statements here }
On the btnSave_Click function, you are getting the data again from the database -see the select * from tbl... code- and you are populating the DataTable again; therefore, it's obvious that there won't be any changes reflected. What you need to do instead is read the Updated DataTable from the page and use it inside the btnSave_Click function to push the updates to the database.
Your question refers to DataGridView which I believe is a User Control on WinForms, but your question is tagged as ASP.NET. Are you referring to a GridView control instead? Either way, both controls should have a way of getting the DataSource bound to them. You should be able to use that DataSource to push the updates to the database.
I hope this pointers are helpful. I cannot be more specific given the code you provided in your question.

Updating DataGridView After row search result

I have a very basic question I want to update DataGridView using this code
private void updateDGV1_Click(object sender, EventArgs e)
{
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
// open connection to database
try
{
cmbl1 = new SQLiteCommandBuilder(datadp1);
datadp1.Update(ds1, "PlotDetails");
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
load_table();
AutoCompleteSizeSearch();
AutoCompletePlotSearch();
AutoCompleteOwnerSearch();
AutoCompleteLocatoinSearch();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
After search for a result using this code
private void plots_txt_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt1);
dv.RowFilter = string.Format("D_ID LIKE '%{0}' AND Area LIKE '%{1}' AND Cat LIKE '%{2}' AND PBS LIKE '%{3}%' AND Name LIKE '%{4}%' AND Size LIKE '%{5}%' AND Location LIKE '%{6}%' AND PlotNo LIKE '%{7}%'", dids_combo.Text, areacs_txt.Text, categorycs_txt.Text, phblses_txt.Text, owners_txt.Text, sizes_txt.Text, locations_txt.Text, plots_txt.Text);
dataGridView1.DataSource = dv;
}
After getting result of search I couldn't been able to update searched result.
updateDGV1_Click works fine on the whole DGV but not on Searched result like in below image
After search,result not updating
I would actually recommend using the TableAdapter to communicate with your database instead of generating a connection in that fashion. This will also allow you to easily update your DataGridView with the contents of the TableAdpater Query (Search) that you want to preform. I wish I could go into more detail but I'm in a hurry at the moment I will provide links explaining this better below.
https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx
I personally use TableAdapters to connect databases in my projects, but I have found a solution that may also allow you to keep your code the way it is for the most part.
http://www.codeproject.com/Articles/14249/How-to-populate-DataGridView-GridView-with-SQL-sta
What you will need to do when you want to preform a search on the current working DataSet. This code is an example I haven't tested it.
string conn_str = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
string sql_str = “select * from table1”;
SqlDataAdapter data_adapter = new SqlDataAdapter(sql_str, conn_str);
SqlCommandBuilder cmd_builder = new SqlCommandBuilder(data_adapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
// This line populates our new table with the data from our sql query
data_adapter.Fill(table);
db_binding_source.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
data_grid_view.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
data_grid_view.ReadOnly = true;
// finally bind the data to the grid
data_grid_view.DataSource = db_binding_source;
Here is also another answer on SO similar to what you're asking
How do I Update/Reload DataGridView BindingSource?

Datagridview sorting a specific column

I have 2 datagridview's that i am trying to sort by one specific column. What I am trying to do is when the program starts I want the DGV to automatically sort by one column by descending. I have been searching and I cannot seem to find what I am looking for.
Here are images of what I am asking. I want the journalID column to start at highest first and descend from there.
Thanks in advance
private void Form1_Load(object sender, EventArgs e)
{
string connectionstring = #"Data Source=|DataDirectory|\Database1.sdf";
SqlCeConnection connection = new SqlCeConnection(connectionstring);
SqlCeCommand command = new SqlCeCommand(" SELECT * FROM journalTbl ORDER BY journalId DESC ;", connection);
try
{
SqlCeDataAdapter adapter = new SqlCeDataAdapter();
adapter.SelectCommand = command;
DataTable datatable = new DataTable();
adapter.Fill(datatable);
BindingSource bindingsource = new BindingSource();
bindingsource.DataSource = datatable;
dataGridView1.DataSource = bindingsource;
adapter.Update(datatable);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Create a connection to the database and select the desired table via
a command
Include specific functions in the command (in this case ordering by journalId Desending)
Create a data adapter to allow communication between the dataset and the datasource
Create a datatable and fill via the data adapter
Create a binding source and assign it to the datatable
Set the datagridview datasource as the binding source.
Update the adapter
Order By SQL - SQL Reference
Order By clause C# MSDN Reference
Please Note: Order by will automatically order by Ascending. I am also using Sql Compact Edition.
I will just add these lines on your Form1_Load(...) method.
DataGridViewColumn columnToSort = dataGridView1.Columns["ColumnNameToSortGoesHere"];
dataGridView1.Sort(columnToSort, ListSortDirection.Descending);
You don't should use Code Behind. You should study MVVM model and Linq library . You work will be better and will be cleaner.
In Model MVVM you solution for this problem is
In your ViewModel
private ObservableCollection<string> _listModelBinding;
public ObservableCollection<string> ListModelBinding
{
get { return _listModelBinding; }
set { _listModelBinding= value; RaisePropertyChanged("ListModelBinding"); }
}
public MainViewModel()
{
ListModelBinding = ListModelBinding.OrderBy(x => x.ToString());
}
In your xaml simply create binding
<DataGrid ItemsSource="{Binding ListModelBinding}" />
That's it.
You can use MVVM in your project using MVVM Light NuGet.

C# Database Displaying Relevant Data in Textboxes

I'm stuck with something and I'd appreciate it if anyone can assist me.
I have a simple MS Access database that's linked to my program. The first thing I did was fill a combobox with one of the fields in my database ("Product Description").
What I'd like to do is when a user selects an item in the combobox, all the other fields in the record be displayed in text boxes.
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=XYZDatabase.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
cbxProducts.DisplayMember = "Product Description";
dbConn.Close();
I've considered using possibly SQL or a DataReader, though I'm really not sure.
This is the event where I want the textboxes to be filled. I'm literally stuck here.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I hope I haven't formatted my question wrong or anything, apologies if I have, this is my first time posting here! Dx
I wonder if your combo box is actually showing data from the DB.
In the first code block after
dbConn.Open()
and before
dbConn.Close()
you should have code like this:
SqlCommand sc = new SqlCommand("select prodid, proddesc from products", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("prodid", typeof(string));
dt.Columns.Add("proddesc", typeof(string));
dt.Load(reader);
cbxProducts.ValueMember = "prodid";
cbxProducts.DisplayMember = "proddesc";
cbxProducts.DataSource = dt;
And then in the second code block you need to fetch the selected Product ID first.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = comboBox1.SelectedValue.ToString();
//Based on ID make a sql query and fetch the details of that product from the DB.
//Follow the earlier code block to make DB connection and execute query.
//Then populate the data in individual text boxes by looping through the dr.
//I am leaving this deliberately for you to figure out and I am sure you can.
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}

Editing contents of a listbox that is populated by a sql query datasource using c#

I have a list box that is populated by a query result set, i would to give the user the ability to edit the contents of the list box, and update the database back end, how can i achieve this?
public Brand_Manager(Main parent)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString.ToString());
SqlCommand cmd = new SqlCommand("select Brand_ID, Brand_Name from Brand where status=1", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
da.Fill(t);
listBox1.DisplayMember = "Brand_Name";
listBox1.DataSource = t;
listBox1.ValueMember = "Brand_ID";
conn.Close();
}
private void Edit_Button_Click(object sender, EventArgs e)
{
this.Edit_Button.Enabled = false;
object item = listBox1.SelectedItem;
Edit_Brand frm = new Edit_Brand();
this.AddOwnedForm(frm);
frm.ShowDialog();
}
Do you use WPF or WinForms? Anyway you need to investigate Bindings: BindingSource in WinForms or Binding class in WPF (http://msdn.microsoft.com/en-us/library/ms750612.aspx).
Look at DataTable events http://msdn.microsoft.com/en-us/library/system.data.datatable_events.aspx . There is RowChangedEvent. Call update sql command in its handler.
You need to use datagridview for this purpose. It is designed for this purpose. You can assign the datasource to gridview and allow user to edit rows. Then by handling row edited event or by giving the button you can update the database. See an example here

Categories

Resources