how to bind the radcombobox at runtime in asp.net - c#

I have a webpage that has a Telerik RadComboBox in radgrid control on the page,and i have a SqlserverCe database.My issue is how can i write the code to bind the RadCombobox at page load event in asp.net please help me.....

Items are bound to RadComboBox basically in the same way as to an ASP.NET DropDownList.
You can bind the RadComboBox to ASP.NET 2.0 datasources, ADO.NET DataSet/DataTable/DataView, to Arrays and ArrayLists, or to an IEnumerable of objects. And of course you can add the items one by one yourself. With RadComboBox, you'll use RadComboBoxItems instead of ListItems.
In one way or other, you'll have to tell the combobox what is each item's text and value.
Working with Items in Server Side Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadComboBoxItem item1 = new RadComboBoxItem();
item1.Text = "Item1";
item1.Value = "1";
RadComboBox1.Items.Add(item1);
RadComboBoxItem item2 = new RadComboBoxItem();
item2.Text = "Item2";
item2.Value = "2";
RadComboBox1.Items.Add(item2);
RadComboBoxItem item3 = new RadComboBoxItem();
item3.Text = "Item3";
item3.Value = "3";
RadComboBox1.Items.Add(item3);
}
}
Binding to DataTable, DataSet, or DataView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=LOCAL;Initial Catalog=Combo;Integrated Security=True");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Text], [Value] FROM [Links]", con);
DataTable links = new DataTable();
adapter.Fill(links);
combo.DataTextField = "Text";
combo.DataValueField = "Value";
combo.DataSource = links;
combo.DataBind();
}
}
EDIT: RadComboBox in a Grid:
Inside a RadGrid, it is perhaps easiest to use load on demand, by setting EnableLoadOnDemand="True" and handling the OnItemsRequested event.
protected void RadComboBox1_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
string sql = "SELECT [SupplierID], [CompanyName], [ContactName], [City] FROM [Suppliers] WHERE CompanyName LIKE #CompanyName + '%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql,
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
adapter.SelectCommand.Parameters.AddWithValue("#CompanyName", e.Text);
DataTable dt = new DataTable();
adapter.Fill(dt);
RadComboBox comboBox = (RadComboBox)sender;
// Clear the default Item that has been re-created from ViewState at this point.
comboBox.Items.Clear();
foreach (DataRow row in dt.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["CompanyName"].ToString();
item.Value = row["SupplierID"].ToString();
item.Attributes.Add("ContactName", row["ContactName"].ToString());
comboBox.Items.Add(item);
item.DataBind();
}
}
You can also bind the combobox manually in the grid's OnItemDataBoundHandler event:
protected void OnItemDataBoundHandler(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem item = (GridEditableItem)e.Item;
if (!(e.Item is IGridInsertItem))
{
RadComboBox combo = (RadComboBox)item.FindControl("RadComboBox1");
// create and add items here
RadComboBoxItem item = new RadComboBoxItem("text","value");
combo.Items.Add(item);
}
}
}

Related

How to add values from dropdownlist and checkbox to gridview

EDIT: added a code and a image reference `public partial class DodavanjeNamirnice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtTemp = new DataTable(); ;
dtTemp.Columns.Add(new DataColumn("Namirnica", typeof(string)));
dtTemp.Columns.Add(new DataColumn("Mjerna Jedinica", typeof(string)));
Session["Data"] = dtTemp;
}
}
protected void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source =.\\SQLEXPRESS; Initial Catalog = pra; Integrated Security = True"].ConnectionString;
string query = "SELECT * FROM Namirnica";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var dataTableFromSession = Session["Data"] as DataTable;
var dataRow = dataTableFromSession.NewRow();
dataRow["Namirnica"] = DropDownList2.SelectedItem.Text;
dataRow["Mjerna Jedinica"] = CheckBoxList1.SelectedItem.Text;
dataTableFromSession.Rows.Add(dataRow);
Session["Data"] = dataTableFromSession;
GridView1.DataSource = dataTableFromSession;
GridView1.DataBind();
}
}`I got 2 dropdownlists , first one is filtering data in the 2nd,also 1st dropdownlist is connected to sql table as is the other one.
I have a checkbox which displays data from another table.
And my problem is: I want to add values I selected from 2nd dropdownlist and the checkboxlist to gridview in my webform.
I tried adding new columns manually but that ends up with displaying only first value from the dropdownlist, also displays only one value from the checkboxlist.
https://gyazo.com/59ea939b26deb55d3f31e68057249253
Set up a method to change the selected or created cell into a DataGridViewComboBoxCell and then feed it the datasource of your drop down list.
//could be whatever event you want such as the creation of a new DataRow in your DataGridView
private void gridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cb.DataSource = dataSource;
}
You can do a similar thing for the checkbox but new DataGridViewCheckBoxCell() instead. After the user has selected a value you can just switch it back to being a regular cell if wanted.

How would I be able to grab the value from a drop down list control after the control has been bound with a filled data set?

How would I be able to grab the value from a dropdown list control after the control has been bound with a filled data set? Specifically, this control lives in my footer template and when the user tries to add a new row the selected item needs to be retrieved. The problem is after the dropdown list has been populated when you click on "add new" the value always returns null.
ROW COMMAND FUNCTION:
protected void userView_RowCommand(object sender, GridViewCommandEventArgs e)
{
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole");
string sqlCommandText = "INSERT INTO Users(USERNAME, PHONE, EMAIL, ROLEIDFK, DEPTIDFK, ACTIVE) VALUES(#username, #phone, #email, #roleidfk, #deptidfk, #active)";
scmd.Parameters.AddWithValue("#roleidfk", addUserRole.SelectedValue.ToString()); // >>>> Returns "AddUserRole was null"
}
DROPDOWN DATABINDING:
private DataTable GetData (string query)
{
var connection = sqlConnect.connect();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connection.ConnectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
protected void userView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
if ( e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
//query.addDataSetDdl(roles, "DESCRIPTION", "ROLEID", ddlUser);
ddlUser.DataSource = GetData("SELECT * FROM Roles");
ddlUser.DataTextField = "DESCRIPTION";
ddlUser.DataValueField = "ROLEID";
ddlUser.DataBind();
}
The problem is that the FindControl call does not use the correct id of the dropdpwnlist - at least it differs from the one that you use when databinding the dropdownlist:
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole")
vs
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
FindControl returns null if the control cannot be found, so if you use the correct id, the problem should be solved.

SelectedIndex is always 0 in dropdownlist(asp.net c#)

I am retrieving data from table Technology in dropdownlist ddlTechnology .
I have TechnologyId as primary key in the table and values are 1,2,3,4
Now as per the technology,i have to add questions in question bank. but when i select any item in dropdownlist, my SelectedIndex is always 0.
i want TechnologyId from dropdownlist.
i have tried following code but its not working
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
Add button to add question according to selected technology.
protected void btnAdd_Click(object sender, EventArgs e)
{
using (dbDataContext dt = new dbDataContext())
{
Question objQtn = new Question();
objQtn.Question1 = txtQuestion.Text;
objQtn.Option1 = txtOption1.Text;
objQtn.Option2 = txtOption2.Text;
objQtn.Option3 = txtOption3.Text;
objQtn.Answer = txtAnswer.Text;
// below here selectedIndex is always zero..
objQtn.TechnologyId = ddlTechnology.SelectedIndex;
dt.Questions.InsertOnSubmit(objQtn);
dt.SubmitChanges();
txtAnswer.Text = "";
txtOption1.Text = "";
txtOption2.Text = "";
txtOption3.Text = "";
txtQuestion.Text = "";
}
}
Reason1:
Seems like you are binding dropdownlist on every postback. If that is a problem then keeping your load code in !IsPostBack shou work.
if(!IsPostBack)
{
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
}
Reason 2:
In some cases if programmer disables ViewState property of any control/page then also control looses it's value on postback.
Need to bind dropdown list in the below event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Bind your dropdown list
}
}
Please find the code for ref. hope it will help you:
(objQtn.TechnologyId = ddlTechnology.SelectedIndex;)
one of these two is of string type check once.
Index.aspx
<asp:DropDownList ID="ddlCloth" runat="server"></asp:DropDownList>
<asp:Button runat="server" ID="btnSave" OnClick="btnSave_Click" />
Index.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt1 = new DataTable();
dt1.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Name") });
dt1.Rows.Add(1, "Shirt");
dt1.Rows.Add(2, "Jeans");
ddlCloth.DataSource = dt1;
ddlCloth.DataTextField = "Name";
ddlCloth.DataValueField = "Id";
ddlCloth.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(ddlCloth.SelectedItem.Value);
string text = Convert.ToString(ddlCloth.SelectedItem.Text);
int index=Convert.ToInt32(ddlCloth.SelectedIndex);
}

Devexpress Get the value from gridview child

I use this code to generate the data and output it in my gridview
string sql = "Sql Query";
string sqlCredit= "Sql Query";
string sqlCreditPayment = "Sql Query";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
ds.DataSetName = "Receivables";
ds.Tables.Add((con.ShowResult(sql, ref da)).Tables[0].Copy());
ds.Tables[0].TableName = "dtReceivables";
ds.Tables.Add((con.ShowResult(sqlCredit, ref da)).Tables[0].Copy());
ds.Tables[1].TableName = "dtCredit";
ds.Tables[1].Columns[1].ColumnMapping = MappingType.Hidden;
ds.Tables[1].Columns[7].ColumnMapping = MappingType.Hidden;
ds.Tables.Add((con.ShowResult(sqlCreditPayment, ref da)).Tables[0].Copy());
ds.Tables[2].TableName = "dtCreditPayment";
ds.Tables[2].Columns[0].ColumnMapping = MappingType.Hidden;
DataRelation dr0 = new DataRelation("CreditList", ds.Tables[0].Columns["Id"], ds.Tables[1].Columns["DocSupplierId"]);
ds.Relations.Add(dr0);
DataRelation dr1 = new DataRelation("CreditPaymentList", ds.Tables[1].Columns["Id"], ds.Tables[2].Columns["SourceId"]);
ds.Relations.Add(dr1);
slipDashBoard.DataSource = ds.Tables["dtReceivables"];
slipDashBoard.ForceInitialize();
gridView1.BestFitColumns();
Guys. Pls help. i want to achieve something like this when i click on the gridview's children. thnx in advance
The main idea in this case is to obtain an instance of the GridView class which was clicked. XtraGrid creates clones of the pattern View which is created at design time and use these clones to disply data. Here is the code which should work:
GridView gridView = sender as GridView;
var value = gridView.GetRowCellValue(gridView.FocusedRowHandle, gridView.Columns["Num"));
MessageBox.Show(value.ToString());
Since your child GridView is created automatically, there are two approaches:
1) handle the GridControl's Click event handler:
private void gridControl1_Click(object sender, EventArgs e) {
GridControl grid = sender as GridControl;
Point p = new Point(((MouseEventArgs)e).X, ((MouseEventArgs)e).Y);
GridView gridView = grid.GetViewAt(p) as GridView;
if(gridView != null)
MessageBox.Show(gridView.GetFocusedRowCellDisplayText("Num"));
}
2) handle the GridView1 MasterRowExpanded event handler:
private void gridView1_MasterRowExpanded(object sender, CustomMasterRowEventArgs e) {
GridView master = sender as GridView;
GridView detail = master.GetDetailView(e.RowHandle, e.RelationIndex) as GridView;
detail.Click += new EventHandler(detail_Click);
}
void detail_Click(object sender, EventArgs e) {
GridView gridView = sender as GridView;
var value = gridView.GetRowCellValue(gridView.FocusedRowHandle, gridView.Columns["Num"));
MessageBox.Show(value.ToString());
}
If you create your grid on runtime you have an instance like gridview2. Now you can add the click event with gridview2.Click += new EventHandler(gridview2_Click);
Then you will get sth. like this:
void view_Click(object sender, EventArgs e)
{
//take the code from platons post...
}

Selecting an item in the RadioButtonList, how to get a list of items to a ListBox from database in asp.net c#

I have a RadioButtonList and a ListBox. I have bound RadioButtonList to database.
Therefore upon selecting an item in the RadioButtonList, I want to retrieve some data into the ListBox. The code I have tried is :
protected void Page_Load(object sender, EventArgs e)
{
RadioFill();
}
public void RadioFill()
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT DISTINCT Param_Name FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
RadioButtonList1.Items.Clear();
RadioButtonList1.DataSource = dset.Tables[0];
RadioButtonList1.DataTextField = dset.Tables[0].Columns["Param_Name"].ColumnName;
RadioButtonList1.DataBind();
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataAdapter mydata = new SqlDataAdapter("SELECT Value_Option FROM Parameter_Value_Master", con);
DataSet dset = new DataSet();
mydata.Fill(dset, "Table");
ListBox1.Items.Clear();
ListBox1.DataSource = dset.Tables[0];
ListBox1.DataTextField = dset.Tables[0].Columns["Value_Option"].ColumnName;
ListBox1.DataBind();
}
The issue I am facing here is upon selecting an item, the whole panel in which I have placed both my RadioButtonList and ListBox goes invisible.
Kindly help...!! Thankyou...!!
First, change Page_Load method as:
protected void Page_Load(object sender, EventArgs e)ยจ
{
if (!Page.IsPostBack)
{
RadioFill();
}
}
If it not help than post code from your *.aspx file.
Remark: The method RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e),
there is not selecting based on radio button list selected value.

Categories