how can I display a dataBase Table in my multiple column comboBox - c#

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;";

Related

Show data of table when clicking on a value - SelectionChanged

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();
}
}

Windows Forms get data from database and display in label

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];

Editing a datatable and sending it back to a database

With my program I have a datatable that gets populated with records fetched from a database. This is displayed in a datagrid view and when a cell is clicked it loads all the values into textboxes. When a save button is clicked it will then save the textbox values back into the datatable. However how can I send this datatable back to the database and have it update the records?
Here is my code to load the records:
indexRow = e.RowIndex;
DataGridViewRow row = dgv_ReturnSearch.Rows[indexRow];
tb_editFirstName.Text = row.Cells[1].Value.ToString();
tb_editLastName.Text = row.Cells[2].Value.ToString();
tb_editAge.Text = row.Cells[3].Value.ToString();
tb_editPostCode.Text = row.Cells[4].Value.ToString();
tb_editMobNum.Text = row.Cells[5].Value.ToString();
tb_editEmail.Text = row.Cells[6].Value.ToString();
tb_editAllergies.Text = row.Cells[7].Value.ToString();
tb_editDOB.Text = row.Cells[8].Value.ToString();
tb_editGender.Text = row.Cells[9].Value.ToString();
Here is my code to save them
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
newDataRow.Cells[1].Value = tb_editFirstName.Text;
newDataRow.Cells[2].Value = tb_editLastName.Text;
newDataRow.Cells[3].Value = tb_editAge.Text;
newDataRow.Cells[4].Value = tb_editPostCode.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
However this doesn't actually update the database, only the local datatable. When it is loaded again all the changes revert.
Thanks
To load a gridview with data from the database you'll need to use DataTable and DataAdapter then bind the grid. it should look something like this:
private void CustomersBindGrid()
{
using (SqlConnection con = new SqlConnection(mycon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM Customers";
cmd.Connection = con;
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
con.Close();
}
}
Try updating the database directly:
private void SaveEdits_Click()
{
using (SqlConnection con = new SqlConnection(mycon))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE Customers set firstname= #FN , lastname= #LN , age = #AG , postcode= #PC where CustomerID = #CustID";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#CustID", cid);
cmd.Parameters.AddWithValue("#FN", tb_editFirstName.Text);
cmd.Parameters.AddWithValue("#LN", tb_editLastName.Text);
cmd.Parameters.AddWithValue("#AG", tb_editAge.Text);
cmd.Parameters.AddWithValue("#PC", tb_editPostCode.Text);
cmd.ExecuteNonQuery();
}
}
CustomersBindGrid();
MessageBox.show("Information Updated!");
}
}
You need to edit this update command to your columns in the database and get a way to read the customer id so the condition actually work and update the database.
In your posting, you don't write, how your client is developed...
Normally, this would be done with a SQL update command.
Therefore (in the Microsoft universe) the SqlClient (System.Data.SqlClient Namespace) can be used.
As soon as the user press the save button, you overtake the relevant textbox.text values in variables, change datatypes if necessary, generate an SQL update string to update the data on your SQL server.
Example SQL update string:
Update TableName set ColumnName1Text = 'some text', ColumName2Integer = 12, ColumnName.... = ... where ColumnNameKey = KeyToDatatable
Then you submit the SQL command (SQL update string) to the SQL server via SqlClient (SqlCommand).
But therefore you need a unique key for the where clause (in the example KeyToDatatable) so that only the row with the key is updated.
The key normally is queried from the DataTable (with the other fields) to show the data (in your grid) and then taken over to the update command (can be "hided" from the user, that don't has to know the key).
Well I managed to fix it by doing:
DataGridViewRow newDataRow = dgv_ReturnSearch.Rows[indexRow];
dt.Rows[indexRow]["first_name"] = tb_editFirstName.Text;
dt.Rows[indexRow]["last_name"] = tb_editLastName.Text;
dt.Rows[indexRow]["age"] = tb_editAge.Text;
dt.Rows[indexRow]["postcode"] = tb_editPostCode.Text;
dt.Rows[indexRow]["mobile_num"] = tb_editMobNum.Text;
dt.Rows[indexRow]["email"] = tb_editEmail.Text;
dt.Rows[indexRow]["allergies"] = tb_editAllergies.Text;
dt.Rows[indexRow]["DOB"] = tb_editDOB.Text;
dt.Rows[indexRow]["gender"] = tb_editGender.Text;
Logic.SQLQueriesUtility.Adapter.Update(dt);
Instead of what I was doing before, now it works perfectly and any changes are saved back to the database.

Combobox C#, fill with DataTable, but in top the selected ID my database.

Combobox C#, fill with DataTable, but in top the selected ID my database.
My table is PRODUTO with id PRODUTO.PRO_LOCAL
Table LOCAL:
1 - Sapatos
2 - Roupas
3 - Acessórios
PRODUTO.PRO_LOCAL = 2, but my combobox fill with top LOCAL = 1, the first from query.
DataTable that fills the combobox:
public DataTable RetornaLocal()
{
SqlConnection sqlConnection = acessoDadosSqlServer.CriarConexao();
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = "SELECT loc_cod, loc_descricao FROM local ORDER BY loc_descricao";
SqlDataReader sqlDataReader = null;
sqlDataReader = sqlCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(sqlDataReader);
return dataTable;
}
Combobox in Form FrmProduto :
cbLocal.DisplayMember = "loc_descricao";
cbLocal.ValueMember = "loc_cod";
cbLocal.DataSource = localNegocios.RetornaLocal();
I want to FrmProduto in change mode show the ID that is table PRODUTO and not the query returned LOCAL norm
Got it setting the SelectedValue -> produto.pro_local field.
How did :
cbLocal.DisplayMember = "loc_descricao";
cbLocal.ValueMember = "loc_cod";
cbLocal.DataSource = localNegocios.RetornaLocal();
cbLocal.SelectedValue = produto.pro_local ;

SqlDataReader filling column in datagridview

I have been wondering for quiet long time how can I set my SqlDataReader to fill column "pocet" in my datagridview "dtg_ksluzby". I thought that my code should look something like this:
SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE id='"+vyberradek+"'",spojeni); // I also have column "pocet" in table klisluz, vyberradek is string which selectrs id number
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
dtg_ksluzby.Columns["pocet"]; // this part I need to improve to fill
}
Would you please help me to improve my code?
Thanks so much in advance.
Edit for trippino:
In "klisluz" which is in the table that includes columns
(id,akce,subkey,text,pocet). I need to:
select * from klisluz where subkey = '"+vyberradek+"'
Take column pocet and fill it into dtg_ksluzby where i find the text is similar in column "text" in dtg_ksluzby
I hope my description is understandabla, sorry for my weak english.
Do not use string concatenation to build sql commands, (to avoid Sql Injection and parsing problem)
using(SqlConnection spojeni = new SqlConnection(conString))
using(SqlCommand novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz " +
"WHERE id = #id",spojeni);
{
novyprikaz2.Parameters.AddWithValue("#id", vyberradek);
spojeni.Open();
using(SqlDataAdapter da = new SqlDataAdapter(novyprikaz2))
{
DataTable dt = new DataTable();
da.Fill(dt);
dtg_ksluzby.DataSource = dt;
}
}
Use a DataAdapter to load your data from database and pass this DataAdapter instance to the DataSource of your DataGridView
Use something like this:
for (int i = 0; i < dtg_ksluzby.Rows.Count; i++)
{
var row = dtg_ksluzby.Rows[i];
using(var novyprikaz2 = new SqlCommand("SELECT pocet FROM klisluz WHERE text LIKE #t AND subkey=#s", spojeni))
{
novyprikaz2.Parameters.AddWithValue("#t", row.Cells["text"].Value.ToString());
novyprikaz2.Parameters.AddWithValue("#s", vyberradek);
spojeni.Open();
SqlDataReader precti2 = novyprikaz2.ExecuteReader();
if (precti2.Read())
{
row.Cells["pocet"].Value = precti2["pocet"];
}
}
}

Categories

Resources