combobox default value winforms c# - c#

Hi here i want to bind some values to check box dynamically.
dataset ds = //getting emp values form database;
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];
it is working fine. But i want to add
"Select emplyoee" as a default value of check box .
But my check box directly adding values like
a1
a2
a3
like this.
I tried like this
cbemp.Items.Insert(0, "Select emplyoee");
but it is not working
how can i add it?

When you use databinding, you cannot "manually" add or remove items. The only way to achieve what you want using databinding is to insert a row first in the DataTable with the desired value, or to populate the combobox by code (add the "Select employee" item and then iterate of the the DataTable rows to add the records).
Perhaps something like this could work:
// create new row for "Select employee"
DataRow row = ds.Tables["emp"].NewRow();
row["empid"] = -1;
row["empname"] = "Select employee";
// insert the row at the top of the table
ds.Tables["emp"].Rows.InsertAt(row, 0);
// do the databinding
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];
I don't use databinding much, so there may be drawbacks with this that I am unaware of (but I am confident that the community will point that out in that case).

Inserting data in your data source is a bad idea. It promotes breaking your layers' abstractions and may lead to some issues if you are using the same data source elsewhere.
Instead, you can easily extend the ComboBox to show a "Please select" message when it has no item selected.
I blogged about this issue and provided the code here : http://www.byteauthor.com/2010/08/inner-label-in-combobox/

I think you'd have to add it to the underlying datatable (ds.Tables["emp"]) for it to appear as an entry in the list when you're using databound controls.

When your control is data bound you cannot add items manually I think.
To work around this problem you could either add a new item to your data source, or you could add the items manually.

The above accepted solution is better, but one trick that might come in handy sometimes is to Union a "fake" record to the SQL that is returning the recordset for the data-binding. In this case, something like:
select 0 as empid, 'Please select' as empname
union
select empid, empname from emp
order by empid
Of course you will have to protect the database from accidentally writing the "0" record back (e.g. if the user doesn't make a selection), but that isn't too hard.

if ComboBoxStyle is set to DropDownList (so user cannot edit combobox) then the easiest way to make sure the user selects an item is to set selectedIndex=-1, you can always add "Please Select" etc ABOVE the combobox.

In my case ( databinded combobox ) i solved the problem like this. Of course the best way is the Kevin Coulombe one.
ComboBox.SelectedIndex = -1;
ComboBox.Text = "Please, select something";
With a bit of code you can manage this scenario pretty easy.

Related

How to populate one combobox with an SQL dataTable and with an item seperate from that table

Sorry if the title is a bit vague - it is difficult to capture what i want to do in one sentence, so I'll quickly explain what I want to achieve.
I want to bind an SQL table to a comboBox and have all its values (Item names for example) but I also wish to add one of my own items into the same comboBox, separate from the table (For example - "Add new" should then be inserted at the bottom of the list after the SQL table values have been loaded in the comboBox).
Is this possible? If so, how do I do it?
Thanks guys!
You can assign datasource in code-behind like this.
cmb1.DataSource=dt;
cmb1.DataBind();
cmb1.Items.Insert(dt.Rows.Count,new ComboBoxItem("Add New","0"));
cmb1.appenddatabounditems="true";
You can use Insert, you have to specify index and new item to add in list.
cmb1.Items.Insert(tabl.rows.count,"Add new");
OR
ComboboxItem item = new ComboboxItem();
item.Text = "Add new";
item.Value = 0;
cmb1.Items.Add(item);
If you not specify any index it will append at last

Datagridview Sends Text Instead of Value to Update for Combobox

I have a Datagridview bound to a DataSet (a view from my database). In my update function i define an UpdateCommand which takes all the columns and sends them to parameters in the database. Like this:
UPDATE Data.DealDetails
SET MoveFromID = #MOVEFROM, ProductID = #PRODUCT, MoveToID = #MOVETO, ScheduledVolume = #VOL, TransportID = #TRANS,
ScheduledDate = #DATE
WHERE (DetailNo = #DETAILNO) AND (DealID = #DEAL)
So i map that to my database columns and everything works fine until i bind a dataset to a combobox cell in my datagrid view. In that case, i have a display member (A DESC) and an ID, i obviously need to send the ID to the database and therefore set that column as an INT. The problem arises when i actually call my update function. Tt (rightfully) throws an error because it cant translate a string into an int (most likely because it looks at the combobox's text and not the value). Now if i select a value from the dropdown and click another cell, the value member is displayed and the update runs fine.
My Question:
How do i send the value of a datagridviewcell to the update function instead of the text.
i don't think this can be done completely in the designer ... assuming you have your datagridview bound to your dataset and the name of the main table as datagridview.DataMember ... then you can do something like this (assuming the combobox column is the third column in your grid):
DataGridViewComboBoxColumn cb = ((DataGridViewComboBoxColumn)dataGridView1.Columns[2]);
cb.DataSource = dataSet1.Lookup;
cb.ValueMember = "Id";
cb.DisplayMember = "Name";
the update command of the generated dataadapter works out of the box then (I tried with a simple example) ...
PrfctByDsgn gave a good response, but ultimately i figured out the problem was that i caught the DataError event just to silence it (that will learn me) which screwed with the combobox's. I got the error in the first place because my View was sending in string values into the combobox instead of numeric values that it requires.

TableAdapter selected GridView Row and insert?

I am trying to get something of a selected GridView Row which is controlled with TableAdapter. (Visual Studio 2010, ASP.NET)
I have otobas.xsd. Inside that, I have Otobus and Sefer tables and also SeferTableAdapter and OtobusTableAdapter. I fill the gridview like this;
otobasTableAdapters.SeferTableAdapter sef = new otobasTableAdapters.SeferTableAdapter();
otobas.SeferDataTable sefs;
sefs = sef.GetData();
SeferTableAdapter sefers = new SeferTableAdapter();
GridView1.DataSource = sefers.GetData();
GridView1.DataBind();
On the GridView Table, I have Select buttons on each row, therefore, when the user clicks one of the select buttons, I want to know which row it was. And then, I want to get the row like this (however, I can't)
otobas.SeferRow rw = ...?
I don't know how to do that. I tried many things but I couldn't. After I get this rw, I want to do something like;
string id = rw['id'];
string arrival = rw['arrival'];
However, I just couldn't do it. Can you show me a way to do this? I tried to add a row but I also couldn't do it. I don't know how to create a row I think. I tried to do the same as
http://msdn.microsoft.com/en-US/library/5ycd1034%28v=VS.80%29.aspx
but, when I wrote
otobas.SeferRow newRow = otobas... I have a data table named Sefer, but I can't reference it at all. Is it wrong to make an instance of the otobas dataset? Like
otobas oto = new otobas();
otobas.SeferRow sr = oto.Sefer.... ?
Why do I have to create an instance of otobas? I mean I already have it as otobas.xsd I just don't get it.
Haven't used this before but is it possible to implement an event handler for the onlclick event of this grid (in either client side or server side code) where you can make use of the event arguments to find this an other information you are searching for>?

Is there any way to convert a Dataset to a List which can be used as a datasource for a combobox?

I have finished a code sequence to insert data from a DataSet into a combobox, but it seemed like an awful lot of work. I thought there may have been a shorter way, then I thought about this question. Is it possible to convert a set of rows in a column of a table in a dataset to a list which can be entered into a combobox with minimal coding effort?
The approaches I have tried was to use the Dataset.Tables[0].Select() to return a dataRowCollection, but that idea crashed and burned - the combobox didn't want to accept it.
The other approach I tried worked, but it seemed like a similar approach I had with my longer code:
DataSet comboBoxItems = new SQLCommands().GetStockIDs(); //Calls the uspGetStockIDs Stored procedure,Returning 1 Column (StockID from Stock Table)
cbStockID.Items.Clear(); //Clears the Combobox
foreach (DataRow dr in comboBoxItems.Tables[0].Rows) //Then Iterates through the retrieved rows
{
cbStockID.Items.Add(dr.Field<int>(0)); //and places them in the combobox
}
But the code above did not answer my question. This is where I rephrase my question: Is it possible to convert a set of rows in a column of a table in a dataset to a list which can be entered into a combobox with minimal coding effort?
Is there a reason you can't use common data binding in your scenario? This should work:
cbStockID.DataSource = comboBoxItems.Tables[0];
cbStockID.DisplayMember = "{DisplayTableColumnName}"; //Displayed items in the combo box.
cbStockID.ValueMember = "{ValueTableColumnName}"; //Value for items displayed in combo box.

datalist with multiple results, with textboxes and buttons that i want to do sql inserts, how?

i'm in c# ASP.NET and I'm new to all this. trying to teach myself but I'm hung up on something that I suppose should be simple. I couldn't find the answer on here with searches because I guess I don't know the appropriate way to describe what I'm looking for. So i last resorted to bugging you guys for an answer.
Please be very basic, I'm quite new but eager.
I have a datalist returning X number of results from a database (MSSQL) - each result comes with some information, and then 2 textbox's and a button. i want them to be able to enter some information into each box, click a button, and then that is inserted back into my SQL database.
I want the text results from each textbox, along with the id (a sql value returned from the datalist's results) to go with it (so that my insert knows which results this is from)
so my page looks like
text 1 - TEXTBOX - TEXTBOX - BUTTON
text 2 - etc etc
if the guy fills out text 2's 2 textboxes and clicks text2's button, i insert (textbox1.text, textbox2.text, "text 2") into my db
this is what i have in my code behind for the click so far
SqlDataSource commentinsert = new SqlDataSource();
commentinsert.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
commentinsert.InsertCommandType = SqlDataSourceCommandType.Text;
commentinsert.InsertCommand = "INSERT INTO ocomments (cuser, date, ip, blogid, text) VALUES (#cuser, #date, #ip, #blogid, #text)";
commentinsert.InsertParameters.Add("cuser", ((TextBox)DataList1.Controls[0].FindControl("TextBox2")).Text);
commentinsert.InsertParameters.Add("date", DateTime.Now.ToString());
commentinsert.InsertParameters.Add("ip", Request.UserHostAddress.ToString());
commentinsert.InsertParameters.Add("blogid", ((Button)DataList1.Controls[0].FindControl("Button2")).CommandArgument.ToString());
commentinsert.InsertParameters.Add("text", ((TextBox)DataList1.Controls[0].FindControl("TextBox3")).Text);
commentinsert.Insert();
the commandargument in button2 is the ID of the blog entry as returned in original datalist rows. the problem I face here is that this only works for the first returned result and none of the others. I recognize this is due to my use of [0] in the controls list, but i have no idea how to fix this. [clientid] didn't help.
thanks in advance for any help guys.
EDIT: adding some code i tried after a user suggestion, i think this is what he wanted me to do but i'm receiving errors: Object reference not set to an instance of an object.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Button Button2b = (Button)e.Item.FindControl("Button2");
TextBox TextBox2b = (TextBox)e.Item.FindControl("TextBox2");
TextBox TextBox3b = (TextBox)e.Item.FindControl("TextBox3");
SqlDataSource commentinsert = new SqlDataSource();
commentinsert.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
commentinsert.InsertCommandType = SqlDataSourceCommandType.Text;
commentinsert.InsertCommand = "INSERT INTO ocomments (cuser, date, ip, blogid, text) VALUES (#cuser, #date, #ip, #blogid, #text)";
commentinsert.InsertParameters.Add("cuser", TextBox2b.Text);
commentinsert.InsertParameters.Add("date", DateTime.Now.ToString());
commentinsert.InsertParameters.Add("ip", Request.UserHostAddress.ToString());
commentinsert.InsertParameters.Add("blogid", Button2b.CommandArgument.ToString());
commentinsert.InsertParameters.Add("text", TextBox3b.Text);
commentinsert.Insert();
}
You really want to use the ItemCommand event of the DataList to perform the update. Set the DataKeys property to the ID field of your DataRow, grab the DataKey value in the ItemCommand event so you know what row you're updating.
To get a reference to the server control's data, use e.Item.ItemIndex[e.SelectedIndex] to get a reference to the correct row. Inside the ItemCommand event, of course.
Take a look at this example:
http://www.c-sharpcorner.com/UploadFile/anjudidi/208062009050129AM/2.aspx

Categories

Resources