I'm using VS2010,C#, I have a table that its data should be created dynamically (from an SQL server table), I have to add a combobox (with 3 items) to one of the columns, this combo box is also created dynamically, then I give each combo a unique ID, it has autopost back set to off and also enableviewstate and viewstatemode to true and enabled, when users changes values for some combo boxes (each row has a combox), and then presses the submit button, I want to have current state of my comboboxes but their selectedindex is 0 so I cannot use them, what should I do? what are my options? (I find each combobox using FindControl and unique ID of the combobox)
thanks
Please find below answer for your above questions
First of all you need to register onchange event of combobox in Javascript while create dynamic combobox.
Put one hidden field on page
And then put the code in onchange event, set the value in hidden field using Clientid from onchange event and then get the value of hidden field from server side.
you can use postback.. here is a sample code snippet.. if you want to work on postback then then follow this.. else you can follow the approach as Rahul told you..
public partial class DynamicCombo : System.Web.UI.Page
{
DropDownList list;
protected void Page_Init(object sender, EventArgs e)
{
Table table = CreateHtmlTable();
list = new DropDownList();
list.AutoPostBack = true;
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.ID = "cbo";
list.Items.Add(new ListItem("value1", "1"));
list.Items.Add(new ListItem("value2", "2"));
list.Items.Add(new ListItem("value3", "3"));
table.Rows[0].Cells[0].Controls.Add(list);
pnl.Controls.Add(table);
}
private void list_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("<script>alert(\"" + list.SelectedIndex + "\");</script>");
}
protected void Page_Load(object sender, EventArgs e)
{
}
private Table CreateHtmlTable()
{
Table table = new Table();
table.Rows.Add(new TableRow());
table.Rows[0].Cells.AddRange(new TableCell[] { new TableCell(),
new TableCell(),
new TableCell()});
return table;
}
}
Related
I have a dropdownlist on a webform that I fill from a sql query, I then want to be able to select individual items in the dropdown and have corresponding fields from a datatable fill textboxes on the form
Problem is rowSel is returning 0 and the dropdown won't let me select any other item it always snaps back to the first itenm in the list.
Thought this might have something to do with autopostback being set to true, but if I set it to false that causes otheer problems, Not sure what else to try Im a winforms person and very new to asp.net
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
int rowSel = ddClients.SelectedIndex;
txtClient.Text = dsShow.Rows[rowSel["ClientsTableFieldA"].ToString();
}
It should allow me to select a value from the drop down then populate some textboxes with fields from the datatable.
You could try:
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Value.ToString();
}
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Text;
}
As suggested by B. Seberle
DDL items have fields value and text so it depends how you bound the ddl to SQL datasource.
place break point on txtClient.Text = ddClients.SelectedItem.Text see if item list is empty.
it should not be necessary but you can force a ddClient.databind() in page_load if(!Page.IsPostback).
however ddClients_SelectedIndexChanged will only trigger on postback.
I'm querying a database filling a gridview with values, also adding dropdown boxes into each cell within the dataview 'onrowdatabound' so these DDL's are populated when the gridview is populated.
I want to be able to click a button to get values from these DDL's however when the button is clicked postback happens and all the DDL's disappear and it gives me the default value for the DDL.
I assume they dissapear as they're not called on pageload (which I can't seem to do as they're called onrowdatabound)
<asp:GridView id="View" name="Spview" onrowdatabound="populateCellswithDDls" runat="server"></asp:GridView>
Adding the ddl with inside 'populateCellswithDDls' function looping each cell:
e.Row.Cells[i].Controls.Add(DDL1);
The next thing I've have a play with is ViewState and Sessions to save the dropdownlists on postback(Tried making sessions within 'populateCellswithDDls' function as so:
DropDownList DDL1 = new DropDownList();
//I've tried newSkillsMon.AutoPostBack = true; but this just removes them all too
Session.Add("ViewState", View);
Session.Add("DropdownState", DDL1);
I've tried all sorts do to with viewstate and session but unsure where to use them in relation to saving states the 'onrowdatabound' population.
My button currently looks like this:
protected void confirm_Click(object sender, EventArgs e){
{foreach (GridViewRow row in View.Rows)
// if (DDL1.SelectedItem.Value != "Select Item"){
if (IsPostBack)
{
Debug.WriteLine(DDL1.SelectedValue);
}
This just gives me X amount of "Select Item" rather than what i have selected in the DDL
What am I missing, where would I add these sessions to keep the ddl's created by onrowdatabound?
Thanks
When creating dynamic controls, you need to recreate them on every Page Load and that includes a PostBack. So start with binding the GridView data outside an IsPostBack check.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//normally you would bind here
}
//but now bind grid every page load
GridView1.DataSource = Common.LoadFromDB();
GridView1.DataBind();
}
Now in the RowDataBound event make sure the DropDownList has an ID
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//create a dropdownlist and assign an ID
DropDownList DDL1 = new DropDownList();
DDL1.ID = "DDL1";
//add some dummy listitems
DDL1.Items.Insert(0, new ListItem() { Text = "A", Value = "A" });
DDL1.Items.Insert(1, new ListItem() { Text = "B", Value = "B" });
DDL1.Items.Insert(2, new ListItem() { Text = "C", Value = "C" });
//add the control to the row
e.Row.Cells[0].Controls.Add(DDL1);
}
}
Now you can get the value from the correct row on a button click.
protected void Button1_Click(object sender, EventArgs e)
{
//find the dropdownlist in the correct row and cast it back to one
DropDownList DDL1 = GridView1.Rows[i].FindControl("DDL1") as DropDownList;
//display the result
Label1.Text = DDL1.SelectedValue;
}
Something that might work for you instead of trying sessions is to use hiddenfields.
Make a hidden field for each dropdown location and then use javascript to populate the hidden fields with the dropdown values. (Possibly wanting some server side validation on submission)
Something like this with jQuery:
$(".dropdowns").on("change", function () {
$(this).closest('input:hidden').val($(this).val());
});
And in your confirmation:
if (HF_HiddenField1.Value != "Select Item")
I have a classic Form with 3 textboxes and 1 combobox. Combobox shows list of Users and 3 textboxes should contain details about the selected user in the combobox. For selected user I have a special attribute (as shown below) which I am using as data source. This is ok only on the first run. When the form is shown, changing user in combobox has no effect.
public partial class UserAdministration : Form
{
private readonly DataManager _dataManager = DataManager.Instance;
private User _selectedUser;
public UserAdministration()
{
InitializeComponent();
}
private void UserAdministration_Load(object sender, EventArgs e)
{
AddUsers();
textBoxName.DataBindings.Add("Text", _selectedUser, "Name");
textBoxSurname.DataBindings.Add("Text", _selectedUser, "Surname");
textBoxPassword.DataBindings.Add("Text", _selectedUser, "Password");
}
private void AddUsers()
{
var users = _dataManager.UserProvider.GetAll().Select(pair => pair.Value).ToList();
comboBoxUsers.DataSource = new BindingSource { DataSource = users };
comboBoxUsers.DisplayMember = "ListViewText";
if (users.Count > 0)
comboBoxUsers.SelectedIndex = 0;
}
private void comboBoxUsers_SelectedIndexChanged(object sender, EventArgs e)
{
_selectedUser = comboBoxUsers.SelectedItem as User;
}
}
What am I missing? What is wrong with data binding?
to bind your datasource to cb use this code:
comboBoxUsers.DataSource = users (directly to you datasource);
to bind the same data to textbox do it like this:
textbox1.DataBindings.Add("Text", users, "username", true);
the only point is, that you need to link both controls to the same ds instance
I have a form with ONLY a textbox that I wanted to bind to database column.
When I used the 'properties' settings to data-bind that textbox to one column, it created the bindingSource1 and table adapter for me.
When I clicked the SAVE button, I simply added bindingSource1.EndEdit(); and then it saved correctly to the database.
I Have a datagridview that gets data from database and shows to the user,I also have three textboxes through which user can enter the value into the datagrid view if I select an already existing row in the datgrid and then enter value by text boxes it makes the changes and when I push change button changes are made successfully in both db and the datagridview
but if I select an empty row in the datagrid view and try to enter the values I cannot new row is not added to the datagrid view although allow user to add new row is set to true.
private void txtName_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["Name"].Value = txtName.Text;
}
}
private void txtRelation_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["Relation"].Value = txtRelation.Text;
}
}
private void txtID_TextChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.SelectedRows[0].Cells["ID"].Value = txtID.Text;
}
}
Check if your gridview is readonly. If Readonly is true then set it to false to enable user add new row. Another reason might be the "EditMode" property of DataGridView. It should not be "Edit Programatically" if you want to allow user to add new row
You have to double click a row to actually create a new row. However, if you do not want the stress of double clicking, you could make the row select event to perform a click on the row.
My windows form has an ADD button which adds a combo box to the form after each click. The problem is, i am not able to bind it to a table column at run time. Using an existing databinding source selects the same value in all the combo boxes. I am coding in C#
here is the sample code :
ComboBox ocbNext = new ComboBox();
//HAVE set the rest of the properties right, the problem is with the databinding
ocbNext.DataSource = this.dummysubjectBindingSource;
ocbNext.DisplayMember = "sub_name";
ocbNext.ValueMember = "sub_name";
this.Controls.Add(ocbNext);
I added a DataSet to the solution and droped the Employees table (from Northwind) in the designer, which automatically created the employeesBindingSource. I dropped a combobox and a button on the Form and I set the DataSource and DataMember of the combo. Then I handled some events:
private void Form1_Load(object sender, EventArgs e)
{
this.employeesTableAdapter.Fill(this.dS.Employees);
}
private int _i = 0;
private void button1_Click(object sender, EventArgs e)
{
ComboBox combo = new ComboBox();
combo.DataSource = this.employeesBindingSource;
combo.DisplayMember = this.dS.Tables[0].Columns[++_i].ColumnName;
combo.Location = new Point(comboBox1.Location.X, comboBox1.Location.Y + comboBox1.Height * _i);
this.Controls.Add(combo);
}
So on each click, a new combo is added onto the form dynamically right under the previous combo. The combo is also bound to the next column in the Employees table (no boundary checks however).
As you can see, this is pretty easy stuff. Hope this helps.
Okay, so here is a variation of the code that could help you with that other question you asked in the comments of this answer.
It assumes you have a Form with a button and a DataSet with table Employees. On button click it creates a combo, and fills it with data (the Name column of Employees). Each time you add a combo, it gets its own copy of the data (this is important to be able to remove items from one combo at a time). Then, every time you select a value in the combo, the combo is disabled and the other combos don't have that selected value in their list.
private int _i = 0;
private void button1_Click(object sender, EventArgs e)
{
DataSet dataS = dS.Clone();
this.employeesTableAdapter.Fill((DS.EmployeesDataTable)dataS.Tables[0]);
BindingSource bindSource = new BindingSource(dataS, "Employees");
ComboBox combo = new ComboBox();
combo.Name = this.dS.Tables[0].Columns[0].ColumnName + (++_i).ToString();
combo.DataSource = bindSource;
combo.DisplayMember = this.dS.Tables[0].Columns[1].ColumnName; //This column is the Name of Employee
combo.Location = new Point(button1.Location.X, button1.Location.Y + combo.Height * _i);
combo.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
this.Controls.Add(combo);
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is ComboBox && ctrl != sender && ctrl.Enabled)
{
((BindingSource)((ComboBox)ctrl).DataSource).RemoveAt(((ComboBox)sender).SelectedIndex);
}
}
((ComboBox)sender).Enabled = false;
}
This is pretty close to what you require, or easily adaptable to meet your expectations. Enjoy and please select an answer as the accepted one. Thanks!
Option 1: Fill the combobox with strings:
this.comboBox1.Items.Add("Syed");
this.comboBox1.Items.Add("Baqar");
Option 2: Fill the combobox with an array of strings:
this.comboBox1.Items.AddRange(new object[] { "Syed", "Baqar" });
You need to add controls to the parent window first, and then set the data source.
ComboBox ocbNext = new ComboBox();
this.Controls.Add(ocbNext);
ocbNext.DisplayMember = "sub_name";
ocbNext.ValueMember = "sub_name";
ocbNext.DataSource = this.dummysubjectBindingSource;
Should be fine if you create a new local ComboBox variable in the clickevent. If you use a global variable for the ComboBox this might explain your problems. But without a sample how you're doing it's hard to see what's really happening, so think this is just a rough guess