How to access valuemember of the combobox - c#

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

Related

C# System.Data.DataRowView

I am almost there trying to filter my datagridview from a combobox avoiding to using the databinding GUI. My problem is now that I see System.Data.DataRowView in my combobox inxtead of the normal values. The code:
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data SourceXXXXX;Initial Catalog=Studio;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand("SELECT Nome FROM DClub order by Nome", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Nome", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "Nome";
comboBox1.DisplayMember = "Nome";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT *,bell+corp+fasc+app as Obi, bell+corp+fasc+vic+app as Tot,(bell+corp+fasc+vic+app)/5 as Med, (bell+corp+fasc+app)/4 as MedOb FROM DClub order by bell+corp+fasc+vic+app desc";
var c = new SqlConnection("Data Source=DIEGOPC;Initial Catalog=Studio;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove filter")
{
dataView.RowFilter = string.Empty;
}
else
{
dataView.RowFilter = $"Nome = '{comboBox1.Text}'";
}
}
}
}
In your last comment
combo1text contains the values retrieved from the query
is fine however what I meant was what does the string itself look like. I assume it is a string that would match one of the values in the Nome column? Without seeing what this “query” strings values are in the combo box, it is difficult to give a good answer. Below, I added a DataGridView and a ComboBox to a form then populated the DataGridView and ComboBox with two DataTables using some sample data. This seems to work as you describe. I assume the row filter line: dataView.RowFilter = $"Nome = '{comboBox1.Text}'"; is simply filtering on matches in DataTables Nome column. I hope the code below helps.
DataTable dgvData;
DataTable cbData;
public Form1() {
InitializeComponent();
dgvData = GetDVGData();
cbData = GetCBData(dgvData);
dataGridView1.DataSource = dgvData;
this.comboBox1.SelectedIndexChanged -= new System.EventHandler(this.comboBox1_SelectedIndexChanged);
comboBox1.DisplayMember = "Filter";
comboBox1.ValueMember = "Filter";
comboBox1.DataSource = cbData;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
}
private DataTable GetCBData(DataTable inDT) {
DataTable dt = new DataTable();
dt.Columns.Add("Filter", typeof(string));
dt.Rows.Add("Remove Filter");
foreach (DataRow dr in inDT.Rows) {
dt.Rows.Add(dr.ItemArray[1].ToString());
}
return dt;
}
private DataTable GetDVGData() {
DataTable dt = new DataTable();
dt.Columns.Add("Number");
dt.Columns.Add("Name");
dt.Columns.Add("Address");
dt.Rows.Add("1", "John", "Texas");
dt.Rows.Add("2", "Mary", "Florida");
dt.Rows.Add("3", "Tom", "New York");
dt.Rows.Add("4", "Marvin", "Moon");
dt.Rows.Add("5", "Jason", "Holland");
dt.Rows.Add("6", "Teddy", "New York");
return dt;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
if (comboBox1.Text == "Remove Filter") {
dataView.RowFilter = string.Empty;
}
else {
dataView.RowFilter = $"Name = '{comboBox1.Text}'";
}
}

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

System.Data.DataRowView, c#

I've got a problem:
SqlDataAdapter da = new SqlDataAdapter("SELECT dbo.User.name FROM dbo.User", con);
DataTable dt = new DataTable();
comboBox1.DataSource = dt;
da.Fill(dt);
It returned System.Data.DataRowView in every row.
I tried:
comboBox1.ValueMember = "idUser";
comboBox1.DisplayMember = "dbo.User.name"
and I get error:
Cannot bind to the new display member. Parameter name:
newDisplayMember
I want to get idUser and name.
Thanks
You need to return the ID in your SELECT statement and assign the DataTable as the DataSource after you have filled the DataTable:
SqlDataAdapter da = new SqlDataAdapter("SELECT IDUser, Name FROM dbo.User", con);
DataTable dt = new DataTable();
da.Fill(dt);
You can then set up the ComboBox as such:
comboBox1.DataSource = dt.DefaultView;
comboBox1.ValueMember = "IDUser";
comboBox1.DisplayMember = "Name"
UPDATE
If you want to access the selected text or value of the item selected in the ComboBox, then you will need to do something like:
DataRowView drvItem = comboBox1.SelectedItem as DataRowView;
if (drvItem != null)
{
label4.Text = drvItem["ID"].ToString();
label3.Text = drvItem["Name"].ToString();
}
Please use below
SqlDataAdapter da = new SqlDataAdapter("SELECT IDUser, Name FROM dbo.User", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "IDUser";
comboBox1.DisplayMember = "Name";

Adding row by row in GridView in runtime

I am new in C#.I want to add rows in a GridView in runtime. I collect a data from 2 or 3 tables. But whenever I am going to
bind() it with GridView, the last inserted row is overwritten by current one. And GridView shows only the current row.
Is it possible to show both rows one bellow the other? Or Is there any code for doing so.Please suggest me code for that so that i can use it in my project.Thanks.
Answer::First you have to declare a static datatable.And a boolean variable having value initially "true".
And then execute following code--->>>
Here is My code::
protected void btnAdd_Click(object sender, EventArgs e)
{
int coursemasterid = Convert.ToInt32(dlAdmissionCourses.SelectedItem.Value);
int batchmasterid = Convert.ToInt32(dlAssignBatch.SelectedItem.Value);
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
DataTable otable = new DataTable();
otable = DbHelper.ExecuteTable(DbHelper.CONSTRING, CommandType.Text, SQL1, null);
DataRow dr1 = otable.Rows[0];
string coursename = dr1["coursename"].ToString();
int coursefees = Convert.ToInt32(dr1["coursefees"]);
string batchname = dr1["batchname"].ToString();
if (chkadd == true)
{
dtglb = new DataTable(); //here dtglb is a global datatable
dtglb.Columns.Add("coursename", typeof(string));
dtglb.Columns.Add("coursefees", typeof(int));
dtglb.Columns.Add("batchname", typeof(string));
}
foreach (DataRow dr in otable.Rows)
{
dtglb.NewRow();
dtglb.Rows.Add(coursename,coursefees,batchname);
}
chkadd = false;
GridView1.DataSource = dtglb;
GridView1.DataBind();
}
//declaring a datatable global in form
DataTable dtglb=new DataTable();
//In click event
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=EMS;User ID=sa;Password=sa123");
string SQL1 = "SELECT coursename,coursefees,batchname FROM CourseMaster,BatchMaster WHERE CourseMaster.coursemasterid=BatchMaster.coursemasterid and CourseMaster.coursemasterid="+coursemasterid+" and BatchMaster.batchmasterid="+batchmasterid+"";
SqlCommand cmd = new SqlCommand(SQL1, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
//DataColumn faculty = new DataColumn();
da.Fill(ds);
GridView1.DataSourceID = null;
//New Code Added Here
DataRow row = ds.NewRow();
//your columns
row["columnOne"] = valueofone;
row["columnTwo"] = valueoftwo;
dtglb.Rows.Add(row);
foreach(DataRow dr in dtglb.Rows)
{
ds.Rows.Add(dr);
}
//=========
GridView1.DataSource = ds;
GridView1.DataBind();
add rows to DataGridView itself
DataGridViewRow row = new DataGridViewRow();
dataGridView1.BeginEdit();
//your columns
row.Cells["columnOne"] = valueofone;
row.Cells["columnTwo"] = valueoftwo;
dataGridView1.Rows.Add(row);
dataGridView1.EndEdit();

Categories