我有一个网页,在页面上有radrik控件的Telerik RadComboBox,我有一个SqlserverCe数据库。我的问题是如何编写代码来绑定在asp.net的页面加载事件中的RadCombobox请帮助我.....
答案 0 :(得分:11)
项目与RadComboBox的绑定基本上与ASP.NET DropDownList相同。
您可以将RadComboBox绑定到ASP.NET 2.0 datasources,ADO.NET DataSet/DataTable/DataView,Arrays and ArrayLists或IEnumerable对象。当然,您可以自己逐个添加项目。使用RadComboBox,您将使用RadComboBoxItems而不是ListItems。
以某种方式,您必须告诉组合框每个项目的文本和值是什么。
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();
}
}
在RadGrid内部,通过设置 EnableLoadOnDemand =“True”并处理 OnItemsRequested 事件,最简单的方法是按需加载。
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();
}
}
您还可以在网格的 OnItemDataBoundHandler 事件中手动绑定组合框:
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);
}
}
}