I am working on a desktop application that populate the list of all tables containing primary key in a combobox on selecting the corresponding database from another combo box like this
///This function binds the names of all the tables without primary keys in a dropdown cmbResults.
public void GetNonPrimaryKeyTables()
{
//An instance of the connection string is created to manage the contents of the connection string.
var sqlConnection = new SqlConnectionStringBuilder();
//Declare the datasource,UserId,Password
sqlConnection.DataSource = "192.168.10.3";
sqlConnection.UserID = "gp";
sqlConnection.Password = "gp";
//Add the initial catalog to the connection string
sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
//Assign the ConnectionString value to a new variable
string connectionString = sqlConnection.ConnectionString;
//Create the connection object
SqlConnection sConnection = new SqlConnection(connectionString);
//To Open the connection.
sConnection.Open();
//Query to select table_names that doesn't have PRIMARY_KEY.
string selectNonPrimaryKeys = #"SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE <> 'PRIMARY KEY'
ORDER BY
TABLE_NAME";
//Create the command object
SqlCommand sCommand = new SqlCommand(selectNonPrimaryKeys, sConnection);
try
{
//Create the dataset
DataSet dsListOfNonPrimaryKeys = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectNonPrimaryKeys, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
sDataAdapter.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Fill the dataset
sDataAdapter.Fill(dsListOfNonPrimaryKeys);
//Bind the result combobox with non primary key table names
DataViewManager dvmListOfNonPrimaryKeys = dsListOfNonPrimaryKeys.DefaultViewManager;
cmbResults.DataSource = dsListOfNonPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
cmbResults.DisplayMember = "TABLE_NAME";
cmbResults.ValueMember = ("");
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}
But what I should do if I need to replace the combobox with a list view populating the same item when according to the selected database from another dropdown.
Can youguys please help me?
Instead of a ListView, try using a DataGridView, replacing these lines
cmbResults.DataSource = dsListOfNonPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
cmbResults.DisplayMember = "TABLE_NAME";
cmbResults.ValueMember = ("");
with this
dataGridView1.DataSource = dsListOfNonPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
You can set properties on the DataGridView to have it look more like a ListView, for example:
dataGridView1.RowHeadersVisible = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
Edit
Also, looking at your query, if your goal is to get the tables that don't have primary keys, try this:
select t.TABLE_NAME
from INFORMATION_SCHEMA.TABLES t
left join INFORMATION_SCHEMA.TABLE_CONSTRAINTS c
on t.TABLE_SCHEMA = c.TABLE_SCHEMA
and t.TABLE_NAME = c.TABLE_NAME
and c.CONSTRAINT_TYPE = 'PRIMARY KEY'
where t.TABLE_TYPE = 'BASE TABLE'
and c.CONSTRAINT_TYPE is null
The INFORMATION_SCHEMA.TABLE_CONSTRAINTS view also includes rows for FOREIGN KEY, CHECK, and UNIQUE constraints, so your query as it stands now will select the table names associated with any of these constraints.
Related
i'm trying to get my current id from a table pk to insert on another table fk, my next try is set a trigger inside database.
CREATE PROCEDURE `INSERIR CODIGO DISPENSACAO` ()
CREATE TRIGGER `productInsert`
BEFORE INSERT ON `produtos_disp`
FOR EACH ROW
BEGIN
set NEW.ID_PRODISP = (select max(ID)
from dispensacao p
);
END
what I want to set max id from dispensacao table which is going to be inserted from auto_increment on insert to it, on my fk codigo_disp for every row.
Managed to get max id using a combobox as descending order.
used
MySqlConnection connection = new MySqlConnection("connectionString");
string selectQuery = "select ID from dispensacao ORDER BY id DESC LIMIT 1";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbid.DisplayMember = "ID";
Cmbid.DataSource = dt2;
this return the max id from the table and all you need to do is make it invisible so user won't change as it is a combobox
Whenever I click on a name in EmployeeRank1 List listbox I want to get in the EmployeeRank1Information listbox associated data from the table for it. However, I get an exception instead. Screenshots and code used provided below.
Table
WPF Window
Exception
Code I have used
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1InformationTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1InformationTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1Information.DisplayMemberPath = "Salary";
employeeRank1Information.DisplayMemberPath = "Position";
employeeRank1Information.DisplayMemberPath = "Responsibility";
employeeRank1Information.DisplayMemberPath = "Age";
employeeRank1Information.DisplayMemberPath = "YearsInCompany";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.ToString());
}
}
}
You could just pass Id into the query, as that is the primary key of Employee
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue == null) // less nesting to flip the condition
return;
try
{
// only select the columns you need
const string query = #"
select
Id,
Name,
Salary,
Position,
Responsibility,
Age,
YearsInCompany
from EmployeeRank1 e
where e.Id = #id
";
// always use a new connection and dispose it
using (SqlConnection sqlConnection = new SqlConnection(yourConnectionString))
// Create an SqlCommand and connect to the database
using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
{
// always specify parameter type (and length for strings)
sqlCommand.Parameters.Add("#id", SqlDbType.Int).Value = ((DataRow)employeeRank1List.SelectedValue)["Id"];
// how do you get the Id column??
DataTable employeeRank1InformationTable = new DataTable();
conn.Open();
using (SqlDataReader reader = sqlCommand.ExecuteReader())
{
employeeRank1InformationTable.Load(reader);
}
} // close connection as quick as you can
// you can only set one column to display
employeeRank1Information.DisplayMemberPath = "Name";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.Message);
}
}
You have declared where conditions for these without value
AND Salary = #salary AND
Responsibility = #responsibility AND
Position = #position AND
Age = #age AND
YearsInCompany = #yearsInCompany
You need to Fille them before executing the query
sqlCommand.Parameters.AddWithValue("#Salary", <VALUE FROM TABLE>);
Since you have not specified how you fill the gridview or table,
you need to get the following values yourself
Your SQL query contains 6 Conditions.
select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany.
but you have only filled one using -
sqlCommand.Parameters.AddWithValue("#name", employeeRank1List.SelectedValue);
so basically the query is equal to this when clicking on a list item
select * from EmployeeRank1 where Name = <LitsView Item>
AND Salary = UNDEFINED
AND Responsibility = UNDEFINED
AND Position = UNDEFINED
AND Age = UNDEFINED
AND YearsInCompany = UNDEFINED;
now UNDEFINED here makes it a SQL syntax error since the scalar variables are missing. to get it to work, here is a workaround for you to understand how it works-
change this line in your code
string query = "select * from EmployeeRank1 where Name = #name AND Salary = #salary AND Responsibility = #responsibility AND Position = #position AND Age = #age AND YearsInCompany = #yearsInCompany";
to this
string query = "select * from EmployeeRank1 where Id = #name";
after you try this it should work with inaccurate results. to make it work properly fill the rest of the where conditions in your SQL code
Also, use a primary/unique key to locate records instead of using #NAME
I managed to make it work by having multiple listboxes instead of one. Moreover, in the query I selected the id only, which is the primary key and then added multiple try-catch blocks in order to fill those listboxes that I had created. A screenshot of the working program, as well as the code
Program
Code
// a method that shows information for employees that are rank 1
private void ShowEmployeeRank1Information()
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1PositionTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1PositionTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1PositionList.DisplayMemberPath = "Position";
employeeRank1PositionList.SelectedValuePath = "Id";
employeeRank1PositionList.ItemsSource = employeeRank1PositionTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1AgeTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1AgeTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1AgeList.DisplayMemberPath = "Age";
employeeRank1AgeList.SelectedValuePath = "Id";
employeeRank1AgeList.ItemsSource = employeeRank1AgeTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1ResponsibilityTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1ResponsibilityTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1ResponsibilityList.DisplayMemberPath = "Responsibility";
employeeRank1ResponsibilityList.SelectedValuePath = "Id";
employeeRank1ResponsibilityList.ItemsSource = employeeRank1ResponsibilityTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Id = #id";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("#id", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1YearsInCompanyTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1YearsInCompanyTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1YearsInCompanyList.DisplayMemberPath = "YearsInCompany";
employeeRank1YearsInCompanyList.SelectedValuePath = "Id";
employeeRank1YearsInCompanyList.ItemsSource = employeeRank1YearsInCompanyTable.DefaultView;
}
}
catch (Exception e)
{
// show what is the error
MessageBox.Show(e.ToString());
}
}
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
ShowEmployeeRank1Information();
}
}
I want to grab data from database and display in labels based on what the user selects in the list view.
I'm going off an example that does this with two list views, but I don't know how to do it when I'm sending data to a label.
This is the list view example I'm using (my label code is below this)
private void PopulateRecipeIngredients()
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = #RecipeId";
// # is a parameter
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
// whatever recipe is selected in lstRecipes box, get the id of that and pass into query above
command.Parameters.AddWithValue("#RecipeId", lstRecipes.SelectedValue);
// DataTable holds the data return from query
DataTable ingredientTable = new DataTable();
// SqlDataAdapter object adapter fills the ingredientTable DataTable object with results from query
adapter.Fill(ingredientTable);
// Display value of Name ex. salad
lstIngredients.DisplayMember = "Name";
// Id column is how we reference
lstIngredients.ValueMember = "Id";
// connect list box on form to data in recipeTable
lstIngredients.DataSource = ingredientTable;
}
}
MY CODE:
private void PopulateCourseDetails()
{
string query = "SELECT * FROM Course_Info WHERE Id = #CourseId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#CourseId", lstCourses.SelectedValue);
DataTable courseTable = new DataTable();
adapter.Fill(courseTable);
lblCourseId.Text = "Course_id";
lblCourseSection.Text = "Course_section";
lblCourseName.Text = "Course_name";
lblCourseDay.Text = "Course_day";
lblCourseStartTime.Text = "Course_start_time";
lblCourseEndTime.Text = "Course_end_time";
lblCourseProfessor.Text = "Course_professor";
lblCourseProfessorEmail.Text = "Course_professor_email";
lstCourses.ValueMember = "Id";
}
}
lblCourseId.Text = (string)courseTable.Rows[0]["Course_id"]
should work as long as you have one row in the result table
Assuming that your DataTable has now been properly populated, you now have a table with a number of rows.
First you need to pull out the first row
var row = courseTable.Rows.FirstOrDefault();
Now you've got a row with a number of columns. You can access each column by either index or column name.
lblCourseId.Text = row[0];
If you want the label to maintain it's header, you can do something like
lblCourseId.Text = "Course_id: " + row[0];
I want to display many tables of data in my datagridview.
I use combobox to select other tables but it can't read and can't show table, so I set my combobox to its 1st table but every time I refresh the table it always getting back to the table I set
private void UpdateDataGrid()
{
using (IDbConnection dbconnection = new SQLiteConnection(conn))
{
dbconnection.Open();
//the other tables are Electrical and Tools
cbTable.Text = "Plumbing";
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter("SELECT * FROM " + cbTable.Text + "", conn);
ds = new System.Data.DataSet();
dataAdapter.Fill(ds, "Item_InFo");
dgvItems.DataSource = ds.Tables[0];
}
}
I am using multi column in combo box. So,I would like to display a database table like this photo.
I tried the below coding but I get only the table date without the table borders.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req = "select id_amort_fiscal+''+amort_fiscal as combined from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
this is what I get as a result:
any Help please and thanks :D
Is this third party control?
Anyway your query is showing you are only picking 1 column. Try adding more columns in query.
private void affich()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// *******************
// See the new_column2, new_column3 in the below query, replace them
// with your own columns
// ********************
req = "select id_amort_fiscal+''+amort_fiscal as combined, new_column2, new_column3 from amortissementFiscal;";
SqlCommand sql = new SqlCommand(req, connection);
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "amortissementFiscal");
multiColumnComboBox1.DataSource = ds.Tables["amortissementFiscal"];
multiColumnComboBox1.DisplayMember="combined";
multiColumnComboBox1.ValueMember = "combined";
connection.Close();
return;
}
Make sure you have assigned ColumnToDisplay property to your MultiColumnCombobox.
multiColumnComboBox1.ColumnsToDisplay = new String[] {"Combinded Fiscal", "First Name"};
This will bind your column data into particular column. To display the proper column header, I preferred to specify alias in your sql query and try to add more columns in your query.
req = "select (id_amort_fiscal+''+amort_fiscal) As [Combinded Fiscal], FName As [First Name] from amortissementFiscal;";