combobox value not showing in C# - c#

I get problem while loading Combobox value from database. I am using SQLite Database. It only show a single value in Combobox but in my database there is multiple value. So how can i do this.
This is my Code:
Class DatabaseHandler it has two methods which Execute Query and other methods return DataTable object:-
public int ExecuteSql(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
return command.ExecuteNonQuery();
}
public DataTable GetDataTable(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
This is Category Class and this is piece of code where i got a problem:-
private void CategoryName()
{
try
{
String Query = "Select CategoryName from CategoryTable;";
databaseHandler.ExecuteSql(Query);
DataTable dataTable = databaseHandler.GetDataTable(Query);
ProductType.DataSource = dataTable;
ProductType.DisplayMember = "CategoryName";
}
catch (Exception CatID)
{
Console.WriteLine(CatID.StackTrace);
}
}

I think you are assigning a DisplayMember but not ValueMember. Please assign the DisplayValue along with ValueMember.
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

Related

How to access valuemember of the combobox

I have to bind the combo box with the following code:
private void getCompanydata()
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.AppSettings["RL_InventoryConnection"]);
if (con.State == ConnectionState.Closed)
con.Open();
MySqlCommand cmd = new MySqlCommand("select comp_id, concat(comp_name,'-', comp_add) as company from companymaster;", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dr.ItemArray = new object[] {0, "--Select Delivery Location--" };
dt.Rows.InsertAt(dr, 0);
comboBox1.DisplayMember = "company";
comboBox1.ValueMember = "comp_id";
comboBox1.DataSource = dt;
}
In another method, I want to access comp_id which is bound with valueMember. I am trying with the following code, but it’s not working:
private void SaveData()
{
string company = comboBox1.Text.ToString();
int companyid = Convert.ToInt32(comboBox1.SelectedValue);
}
You want to try use combobox1.SelectedValue instead of combobox1.MemberValue.
More Details in the documentation here...
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listcontrol.selectedvalue?view=windowsdesktop-6.0#system-windows-forms-listcontrol-selectedvalue
Similar answer link below...
https://stackoverflow.com/a/6901118/4462984

show data in Listbox c# from sql

I have this code to show data from SQL to listbox in c#
public DataTable get_mada_listbox()
{
DAL.DATAACSESSLAYER dal = new DAL.DATAACSESSLAYER();
dal.open();
DataTable dt = new DataTable();
dt = dal.selectData("get_mada_listbox", null);
dal.close();
return dt;
}
When I call the function:
BL.cls_product prd = new BL.cls_product();
listBox1.DataSource = prd.get_mada_listbox();
The listbox should show
system.data.data row view.
How can I solve it?
i solve my problem by add
listBox1.DisplayMember = "mada_name";
next this
listBox1.DataSource = prd.get_mada_listbox();
thx
This should be your method:
void get_mada_listbox()
{
var connection = ConfigurationManager.ConnectionStrings[name].ConnectionString;
using (SqlConnection connsql = new SqlConnection(connString))
{
connsql.Open();
// Sql Adapter
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM DataTable", connection))
{
// fill a data table
var data_table = new DataTable();
sqlAdapter.Fill(t);
// Bind the table to the list box
listBox1.DisplayMember = "mada_name";
listBox1.ValueMember = "mada_value";
listBox1.DataSource = data_table;
}
}
}

ComboBox SelectedItem from DataTable Winforms C#?

I have a method in my DAL which populates a ComboBox from a DataTable. ComboBox displays correctly and I have a 'Save' button which saves back to my DB, job's a good'un...
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("#id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(#id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedItem = dr["company_int_name"].ToString();
}
}
return "";
}
However obviously when I re-edit the record, this method is called again. Ok, I now have written a ForEach loop which iterates over my DataTable and compares the string in the rows to the Name I am passing in. If the two match I'm setting the
Combo.SeletedItem = dr["company_int_name"].ToString();
However the selectedItem is not being set, presumably I'll need some sort of event to notify the property changed?
Thanks
You have to bind the Combo Box with the ValueMember function and can reflect the combo box with the matched string value as selected
public string populateLookUp(ref System.Windows.Forms.ComboBox Combo, string Id)
{
SqlCommand _comm = new SqlCommand();
_comm.Parameters.AddWithValue("#id", Id);
_comm.CommandText = "SELECT [name] FROM dbo.fnGetName(#id) ORDER BY [name]; ";
_comm.Connection = _conn;
_comm.CommandTimeout = _command_timeout;
DataTable dt = new DataTable();
try
{
SqlDataReader myReader = _comm.ExecuteReader();
dt.Load(myReader);
}
catch
{
MessageBox.Show("Unable to populate Name LookUp");
}
Combo.DataSource = dt;
Combo.DisplayMember = "name";
Combo.ValueMember = "name";
foreach (DataRow dr in dt.Rows)
{
if (dr["company_int_name"].ToString() == Contract.Company_trans_Selling_Entity.ToString())
{
Combo.SelectedValue = dr["company_int_name"].ToString();
}
}
return "";
}

i just try to search the result by the name of school.but the grid view didnt show any thing

this is my code...i just try to search the result by the name of school.but the grid view didnt show any thing.my code is
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
gvResult.DataSource = dtbl;
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
}
protected void Button1_Click(object sender, EventArgs e)
{
gridfill();
}
public DataTable markViewAll()
{
DataTable dtbl = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewAll", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.Fill(dtbl);
return dtbl;
}
public DataTable markViewBySchool(string viewBySchool)
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewBySchool",sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#schoolName", SqlDbType.VarChar).Value = viewBySchool;
sqlda.Fill(dtbClass);
return dtbClass;
}
change as below, there are few problems in your code, why two times databinding to same gridview? even you data bind two times it only show what you set at the last time. i have removed few lines of code and you forgot to call gvResult.DataBind() as well
public void gridfill()
{
markSp spMark = new markSp();
gvResult.DataSource = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataBind();
}
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.Databind(); // You forgot DataBind()
}
Since you have tagged with ASP.Net, you need to call DataBind
gvResult.DataBind();
So your method would be:
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll(); //you are not using this anywhere
gvResult.DataSource = dtbl; // so you can get rid of these two lines
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.DataBind(); // This is missing
}
You should see: ASP.NET data binding overview

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}

Categories