Binding SQL data to Label in WPF - c#

Is there a way to data bind SQL data to a label in WPF?
I have a SQL database that has a total of summed up data. I want to display the last column's data to a label. So if the column reads "10" then I need the label to display "10".
Here is the code I've tried:
C#:
SqlConnection con = new SqlConnection(myconnectioninfo);
SqlCommand scom = new SqlCommand();
scom.CommandText = "SELECT TOP 1 [TotalIncidents] FROM sixMonthReport ORDER BY [TotalIncidents] DESC"
Object temp = cmd.ExecuteScalar();
label.Text = temp.ToString();
Most appeared to work until I get to the label.text portion which is not an option in WPF.
I can't seem to find any information on much of WPF / labels any help is appreciated.

label does not have a text property but it does have content one, so you can try something like:
Object temp = null;
using (SqlConnection con = new SqlConnection(myconnectioninfo))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT TOP 1 [TotalIncidents] FROM sixMonthReport ORDER BY [TotalIncidents] DESC", con))
{
temp = cmd.ExecuteScalar();
}
}
label.Content = temp?.ToString();

Related

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.

Loading Image through label

I am trying to load an image through label using this code
private void getData()
{
SqlConnection conn = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
conn.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT empName,empLname,empMi,empImage
FROM employees
WHERE empName = '"+ ddlAvail.SelectedItem.Value.ToString() +"'", conn);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblName.Text = rdr.GetValue(0).ToString();
lblLname.Text = rdr.GetValue(1).ToString();
lblMi.Text = rdr.GetValue(2).ToString();
lblImage.Text = "<img runat='server' src='" + rdr.GetValue(3).ToString() + "'></img>";
}
}
conn.Close();
}
every time I select a dropdownlist value it generates me set of sql data.My only problem is the image.Cause it wont load any image at all.The filepath on my visual studio and image name is correct.
This is an example of my image
../Images/Profile/logo.jpg
I save the images filepath on my database.
Your code looks fine
Make sure the file path your are retrieving from the database exists and the path isn't returning any unwanted characters.
That is:
rdr.GetValue(3).ToString() //should return the right path (string)
It should be fine. Hope this helped
It won't ever show the image because all that your code is doing is setting the text on the label.
If you want to display the image try this , or this.

how to populate textbox with new Row ID in windows form

I'm creating a windows form and currently in the process of creating the "create member" form.
Now i wish to show to the user inputting data what the new members ID will be. So i thought of trying to show the new row ID within a text box. So if we take the example below, when the form loads, the new member ID should be shown in the textbox
I've tried to attempt it below but having difficulty getting the result from the sqlCommand. Or maybe im going the wrong way around doing it ha
Can anyone see how i can apply the id upon load?
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT * FROM Users WHERE UserID=(SELECT MAX(UserID) FROM Users", connection))
{
//cmd.Parameters.Add("#MYVALUE", SqlDbType.VarChar).Value = comboBox1.Text;
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = // result from the SQLCommand but i dont know how to get it
You can access current row cells by indexing DataReader with columns names, like this txtMemberId.Text = thisReader["UserID"]; //here you should do increment. But honestly, generating Id in select max(id) + 1 manner is odd, GUIDs nad Autoinc integer is more commonly used in our days.
Your MAX+1 should looks like:
private void frmAddMember_Load(object sender, EventArgs e)
{
using (var connection = new SqlConnection(Properties.Settings.Default.BioEngineeringDB))
{
connection.Open();
using (var cmd = new SqlCommand("SELECT (COALESCE(MAX(UserID), 0) + 1) as UserID FROM Users", connection))
{
SqlDataReader re = cmd.ExecuteReader();
if (re.Read())
{
txtMemberId.Text = re["UserID"].ToString();
remove your autoinc id column and add a guid id col instead. then you can generate the Id on the client with Guid.NewGuid().ToString()
Assuming your ID column is being generated by the database (auto increment, etc...) just get the ID when you create the record.
var cmd = new SqlCommand("INSERT INTO User(FirstName) VALUES('bob')");
var id = (int) cmd.ExecuteScalar();
txtMemberId.Text = id.ToString();

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

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

Categories

Resources