combobox data bind (C# winforms) - c#

where is the problem with this code? When i start the program there is no values to choose from comboBox. There is no problems with compiling and starting an application. I have no idea what is wrong here. Maybe someone have solution for this problem.
Link to pastebin https://pastebin.com/pASVNWq
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace parKing_new
{
public partial class editClient : Form
{
public editClient()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{}
//Load customer ID to a combobox
private void LoadCustomersId()
{
var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT clientID FROM clients";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the
combobox's items
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString("clientID"));
}
}
}
}
}
//Load customer details using the ID
private void LoadCustomerDetailsById(int id)
{
var connectionString =
"Server=localhost;Port=3306;Database=ewisys;Uid=root;password=;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT clientID, name, surName FROM clients WHERE
Id = #clientID";
using (var command = new MySqlCommand(query, connection))
{
//Always use SQL parameters to avoid SQL injection and it
automatically escapes characters
command.Parameters.AddWithValue("#clientID", id);
using (var reader = command.ExecuteReader())
{
//No customer found by supplied ID
if (!reader.HasRows)
return;
ClientIDTextBox.Text =
reader.GetInt32("clientID").ToString();
nameTextBox.Text = reader.GetString("name");
surNameTextBox.Text = reader.GetString("surName");
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var clientID = Convert.ToInt32(comboBox1.Text);
LoadCustomerDetailsById(clientID);
}
}
}

Add this to your code.
The reason behind this is that when you launch your application, nothing is calling LoadCustomersId() function to populate the data on your comboBox. So use the Load event handler and populate your combobox from there:
private void editClient_Load(object sender, EventArgs e)
{
LoadCustomersId();
}

I think you have only defined LoadCustomersId() method, but you are not calling it from anywhere.you need to call the method

Related

Is there any solution "Gridview shows only one data after update new entry."?

Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);

Are there any ways to refresh a listview every 5 or 3 seconds without using the timer?

I have a form which is running on the other laptop, this is the kitchen side where all the orders will go through after buying in my POS (which is running on the other laptop also) side.
Now my listview in the kitchen side refreshes after 5 seconds 'using the timer', are there any options or ways to refresh the listview without using the timer so that the 'Focus' when I select an item inside the listview will not disappear?
This is the my code:
public Kitchen()
{
InitializeComponent();
listView2.Columns.Add("ORDERS", 800);
listView2.View = View.Details;
System.Windows.Forms.Timer timer_1 = new System.Windows.Forms.Timer();
timer1.Interval = 5000;
timer1.Tick += new System.EventHandler(timer1_Tick);
timer1.Start();
}
private void dinein(String tblnmber)
{
String[] row = { tblnmber };
listView2.Items.Add(new ListViewItem(row));
}
public void loaddinein()
{
listView2.Items.Clear();
string sq = "select tblnmber as [ORDERS] FROM Kitchen Group By tblnmber";
cmd = new SqlCommand(sq,con);
try
{
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dinein(row[0].ToString());
}
con.Close();
dt.Rows.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
loaddinein();
}
Well your question is really how do I refresh an existing list of items without changing order or focus? not anything to do with timers.
To accomplish that when you fetch the data from the DB again, you need to determine which items have changed in the list (compare the text of your model to an item in the list) and simply update the Text of those items. Overwriting a ListViewItem's Text property won't change selection/focus or re-ordering by default.
Don't clear out the ListView and repopulate otherwise focus/selection will change.
A timer is still perfectly valid to use.
Pooling continuously to the DB server is not a good approach, you can go for either of the two approaches.
Raise a change message using trigger to MSMQ, and subscribe to the
MSMQ for new messages. For more details on the implementation you
can check here
Monitoring the data changes using SqlDependency, for more details you can check here
Note: Both the approaches have it own pro/cons. For example if the number of listeners are more, in that case SQL Dependency will hit the performance.
Hi guys i've already watch and read some tutorials , and implement it, unfortunately sql dependency is not firing to my datagridview nor listview. I've also enabled the broker.
This is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
//ALTER DATABASE HOB SET ENABLE BROKER
namespace DemoSQL
{
public partial class Form1 : Form
{
public string m_connect = #"Data Source=DESKTOP-3B561M1;Initial Catalog=Users;Integrated Security=True";
SqlConnection con = null;
public delegate void NewHome();
public event NewHome OnNewHome;
public Form1()
{
InitializeComponent();
try
{
SqlClientPermission ss = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
ss.Demand();
}
catch (Exception)
{
throw;
}
SqlDependency.Stop(m_connect);
SqlDependency.Start(m_connect);
con = new SqlConnection(m_connect);
}
private void Form1_Load(object sender, EventArgs e)
{
OnNewHome+=new NewHome(Form1_OnNewHome);//tab
//load data vao datagrid
LoadData();
}
public void Form1_OnNewHome()
{
ISynchronizeInvoke i = (ISynchronizeInvoke)this;
if (i.InvokeRequired)//tab
{
NewHome dd = new NewHome(Form1_OnNewHome);
i.BeginInvoke(dd, null);
return;
}
LoadData();
}
//Ham load data
void LoadData()
{
DataTable dt = new DataTable();
if (con.State==ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName from dbo.Uss", con);
cmd.Notification = null;
SqlDependency de = new SqlDependency(cmd);
de.OnChange += new OnChangeEventHandler(de_OnChange);
dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
dataGridView1.DataSource = dt;
}
public void de_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency de = sender as SqlDependency;
de.OnChange -= de_OnChange;
if (OnNewHome!=null)
{
OnNewHome();
}
}
}
}

Event not firing with dynamically placed user control asp.net c#

I’m trying to create a webpage that displays dynamically placed WebUserControls depending on a question type that is returned from and SQL server. When you press a button on the usercontrols it checks the result from the usercontrol using the procedure “CheckResult”. For some reason when you click on the buttons within the usercontrols ("cmdProcess") the Event “CheckResult” does not fire. What am I doing wrong please?
The User control code is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
// Delegate declaration
public delegate void PhotoUploaded(string strFilename, String FailureMessage, string strFabricationNo, string strPartNo, string strBatchNo, string strPartSN, string strSTK_SerialNo, string strSTK_PartNo);
// Event declaration
public event PhotoUploaded Resultresponse;
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void cmdProcess_Click(object sender, EventArgs e)
{
if (Resultresponse != null)
{
Resultresponse("Passed", "", "", "", "", "", "", "");
}
TextBox1.Text = "";
}
}
}
And the main ASPX page that the usercontrols are placed on is: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Load(object sender, EventArgs e)
{
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
Session["RunInsp"] = false;
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
}
Session["DataTableW"] = dtQuestionSet;
}
void CheckResult(string Result, string FailureMessage, string FabricationNo, string PartNo, string BatchNo, string PartSN, string STK_SerialNo, string STK_PartNo)
{
Label1.Text = "You Answered: - " + Result;
if ((Convert.ToInt32(Session["Counter"]))>= Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
Session["RunInsp"] = false;
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
//If the inspection hasn't been completed carry on and ask next question.
if (Convert.ToBoolean(Session["RunInsp"]) == true)
{
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
dtQuestionSet.Clear();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
Session["RunInsp"] = true;
}
protected void RunInspection()
{
//Populate the user controls
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT2.Resultresponse += new WebUserControl2.PhotoUploaded(CheckResult);
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
QT3.Resultresponse += new WebUserControl3.PhotoUploaded(CheckResult);
break;
}
//Add the usercontrols to the form
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
//Need to set the visability of the usercontrol so it only shows the usercontrol that is displaying the question
QT2.Visible = false;
QT3.Visible = false;
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.Visible = true;
break;
case "2":
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}
Try initializing the controls in OnPreInit rather than load. Controls binding is done in OnPreInit.
See the page lifecyle events MSDN Reference

How to populating labels with corresponding row data from selections in a combobox in a c# form

I have a c# form. I have a ComboBox that is the controller. I want to populate labels to display fields from the same row as the selected item in my drop down list.
for example, items is my ComboBox, so if I select an item from my ComboBox, then I want "description" to populate my label, as item ComboBox is selected.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql; //Dir used to connect to sql DB
using System.Data.SqlClient; //Dir used to connect to sql DB
namespace items_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'syteLine_AppDataSet.item' table. You can move, or remove it, as needed.
this.itemTableAdapter.Fill(this.syteLine_AppDataSet.item);
//creating the connection to database.
SqlConnection con_str = new SqlConnection("Data Source=SL1;Initial Catalog=SyteLine_App;Integrated Security=True");
SqlDataAdapter dta_ad = new SqlDataAdapter("SELECT item, description, lead_time, product_code, p_m_t_code, stocked, matl_type, family_code, low_level, days_supply, order_min, order_mult, plan_code,accept_req, shrink_fact, var_lead, decifld1, decifld2, decifld3, datefld, pass_req, order_max, uf_Active, uf_BoughtOff, uf_Old, uf_ProjectEngineer FROM dbo.item", con_str);
DataTable dta_tbl = new DataTable();
dta_ad.Fill(dta_tbl);
for (int i = 0; i < dta_tbl.Rows.Count; i++)
{
cbxItem.Items.Add(dta_tbl.Rows[i]["item"]);
}
}
public void cbxItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxItem.SelectedIndex == -1)
{
label1.Text = string.Empty;
}
else
{
label1.Text = cbxItem.SelectedItem.ToString();
}
}
}
}
I would only retrieve 1 or 2 columns on page load, JUST to show the dropdown.
I would do a second query in the cbxItem_SelectedIndexChanged method passing in the selected value:
DataTable dt = SomeFunctionThatGetsTheDataForTheSelectedValue(cbxItem.SelectedValue)
lblDescription = dt.Rows[0]["Description"];

Updating a database in window form and c#

I am adding records to my database via a windows form. But when ever I add a new record it doesnt update until I close the app and then start again. Even though I think I am telling it to update (Im obv not!!)
Do I need a new varibale to update the database? Im a little stuck.
EDIT: All code on this..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace MediaManagementSystem
{
public partial class AddMedia : Form
{
//database var
OleDbConnection m_cnADONetConnection = new OleDbConnection();
OleDbDataAdapter m_daDataAdapter;
OleDbDataAdapter m_cbCommandBuilder;
DataTable m_dtMedia = new DataTable();
int m_rowPosition = 0;
public AddMedia()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
//load up file dialog and find media
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
//add media file name to file path text box
txtFilePath.Text = addFileDialog.FileName;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void AddButton_Click(object sender, EventArgs e)
{
//add the new record to the database
DataRow drNewRow = m_dtMedia.NewRow();
drNewRow["FilePath"] = txtFilePath.Text;
drNewRow["Subject"] = txtSubject.Text;
drNewRow["Title"] = txtTitle.Text;
drNewRow["Keywords"] = txtKeywords.Text;
drNewRow["MediaType"] = AddComboBox.Text;
m_dtMedia.Rows.Add(drNewRow);
m_daDataAdapter.Update(m_dtMedia);
m_rowPosition = m_dtMedia.Rows.Count - 1;
this.ShowCurrentRecord();
this.Close();
}
private void AddMedia_Load(object sender, EventArgs e)
{
//link to the database and conect to database
m_cnADONetConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Max\Documents\Visual Studio 2010\Projects\MediaManagementSystem\MediaManagementSystem\bin\Debug\MediaDB.mdb";
m_cnADONetConnection.Open();
OleDbConnection objConnection = new OleDbConnection(m_cnADONetConnection.ConnectionString);
m_daDataAdapter = new OleDbDataAdapter("Select * From Media", m_cnADONetConnection);
OleDbCommandBuilder m_cbCommandBuilder = new OleDbCommandBuilder(m_daDataAdapter);
m_daDataAdapter.Fill(m_dtMedia);
m_daDataAdapter.Update(m_dtMedia);
}
public void ShowCurrentRecord()
{
m_daDataAdapter.Update(m_dtMedia);
if (m_dtMedia.Rows.Count == 0)
{
txtFilePath.Text = "";
txtSubject.Text = "";
txtTitle.Text = "";
txtKeywords.Text = "";
AddComboBox.Text = "";
return;
}
txtFilePath.Text = m_dtMedia.Rows[m_rowPosition]["FilePath"].ToString();
txtSubject.Text = m_dtMedia.Rows[m_rowPosition]["Subject"].ToString();
txtTitle.Text = m_dtMedia.Rows[m_rowPosition]["Title"].ToString();
txtKeywords.Text = m_dtMedia.Rows[m_rowPosition]["Keywords"].ToString();
AddComboBox.Text = m_dtMedia.Rows[m_rowPosition]["MediaType"].ToString();
}
}
}
It would best if you use DataSet and then update the records in it. Finally you need to call AcceptChanges() after the update() command to commit the changes with dataset something as below also reload the data after to enter to get the recent data info:
dataset.AcceptChanges()
After you open AddMedia form from your MAIN form, you need to RALOAD all your records again. Look how the form is doing it when it opens and do the same AFTER you open your AddMedia form ;)

Categories

Resources