System.Data.DataRowView, c# - 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";

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

How to filter DataTable with condition where int ID is null

I have gridview and
GridViewName.DataSource = table;
table values:
string myConnection = ConfigurationManager.ConnectionStrings["vizitka"].ToString();
string Query_sel = MySqlString;
MySqlConnection conDataBase = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase_sel = new MySqlCommand(Query_sel, conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase_sel;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
TableName.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I get Values:
then, I'm adding new row to table:
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
and getting values with empty cells (also ID is empty and it's good for me):
then:
GridViewName.DataSource = table;
all is good, but then if I want to delete from table this new created row, I cannot. I'm trying to filter and bind again GridViewName.
DataView view = new DataView(table);
view.RowFilter = "CONVERT(id, System.String) = null or CONVERT(id, System.String) = ''";
Console.WriteLine(view);
but I'm getting empty table. Why?
I assume the ID is numeric. You don't want = null, you want IS NULL, which is how you check for nulls in both DataView (and also in SQL).
view.RowFilter = "ID IS NULL";

C# DropDownList listing number value

I have a dropdownlist that fills like:
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
Now I want to read the listing number of the selected item(in order to place it in a query).
So, while my dropdownlist has values like "Oxford University", "MIT University", "Simon Fraser University" etc, I want clicking an item from the list, store the value of this item in the list. To be more specific, if clicking the first item, then
int number = 1. if clicking the second item, then
int number = 2.
Is it possible to be done with something like:
DropDownList1.SelectedItem.????;
Thank you for your time!
You didn't bind item's value to dropdownlist, so you need to bind it.
like this
DropDownList1.DataValueField = ds.Tables[0].Columns["Column name that contain the value of Item"].ToString();
and then you can use to get it's value like as follow
string item_value = DropDownList1.SelectedValue;
If you want selected Value then use
DropDownList1.SelectedValue
and if you want selected item then use
DropDownList1.SelectedItem
In addition to Nitin Kumar answer, selected item text can be obtained by:
var selectedText = DropDownList1.SelectedItem.Text;
Selected Value
var selectedValue = DropDownList1.SelectedValue;
cmd.CommandText = "select * from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["schoolName"].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns["SomeValueColumn or id column"];
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
and then you can use...
string id = DropDownList1.SelectedValue.ToString();
Try this.
cmd.CommandText = "select id,schoolName from dbo.pelischool";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt );
if (dt != null)
{
if (dt.Rows.Count > 0)
{
ddlPosition.DataSource = dt;
ddlPosition.DataTextField = "schoolName";
ddlPosition.DataValueField = "Id";
ddlPosition.DataBind();
}
}

Filling of ComboBox with Dataset

When am trying to fill Combobox
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
da.Fill(ds1, "Mt_Post");
// The table has only one row
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "Mt_Post";
It bind But shows instead of data it having System.Data.DataRowView
What is the wrong this code Please anyone tell me
Replace Mt_Post in comboBox1.DisplayMember = "Mt_Post"; with the name of column whose value you would like to display.
I hope the following sample helps;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.AcceptChanges();
DataRow dr0 = dt.NewRow();
dr0[0] = "Kadir Sumerkent";
dr0[1] = "kadir#sumerkent.com";
DataRow dr1 = dt.NewRow();
dr1[0] = "Kadir Sumerkent 2";
dr1[1] = "kadir#sumerkent2.com";
dt.Rows.Add(dr0);
dt.Rows.Add(dr1);
dt.AcceptChanges();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Email";
comboBox1.DataSource = dt;
Let's try this:
Suppose your Stored Procedure is like the code below:
SELECT
Users.User_name AS username
Users.User_Code AS userID
FROM Users
-- WHERE CONDITONS ARE APPLIED
Now in order to Fetch this DataSet you are going to do as follows:
// YOUR OWN CODE
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
// JUST FILL THE DataSet in THIS WAY
da.Fill(ds1);
// JUST TO MAKE SURE WE HAVE AN EMPTY COMBOBOX
comboBox1.Items.Clear();
comboBox1.DataSource = null;
// NOW POPULATE comboBox1 LIKE THIS
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "username";
comboBox1.ValueMember = "userID"
}

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