Controls .DataSource / .Databind not function correctly
Just started a new ASP project and for some reason my drop down datasource and databind doesn't seem to be working properly when everything is there and no errors are thrown.
List<ProductEntity> products = new List<ProductEntity>();
ProductManager productManager = new ProductManager();
products = prod开发者_如何学运维uctManager.GetProducts();
ddlProducts.DataSource = products;
ddlProducts.DataBind();
the asp code.
int colCounter = 0;
List<ProductEntity> products = new List<ProductEntity>();
DataTable dt = new DataTable("Products");
SqlDataReader dr = null;
SqlCommand cmd = new SqlCommand();
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["FIConnection"].ConnectionString))
{
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.SV_GetProduct";
cn.Open();
dt.Load(dr = cmd.ExecuteReader());
cn.Close();
}
foreach (DataRow rows in dt.Rows)
{
ProductEntity prod = new ProductEntity();
foreach (DataColumn columns in dt.Columns)
{
if (colCounter == 0)
{
prod.ProductDesc = Convert.ToString(rows[columns]);
colCounter++;
}
else if (colCounter == 1)
{
prod.FormingCode = Convert.ToString(rows[columns]);
colCounter = 0;
}
}
}
return products;
and the GetProducts code.
When stepping through the project GetProducts successfully returns data. I am just unable to bind it even though everything looks to be in order. My attempt at databinding is on the Page Load even which I have done before but doesn't seem to be working this time. So confused, any help would be greatly appricated.
Not completely understand your problem. Also mention the following properties of dropdownlist ddl
ddl.DataTextFeild="Feild to Display";
ddl.DataValueFeild="Feild ID";
May be this will help you
namespace WebApplication3
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = GetProducts();
DropDownList1.DataTextField = "FormingCode";
DropDownList1.DataValueField = "ProductDesc";
DropDownList1.DataBind();
}
private List<Product> GetProducts()
{
List<Product> ret = new List<Product>();
for (int i = 0; i < 100; i++)
{
Product p = new Product();
p.ProductDesc = i;
p.FormingCode = i.ToString();
ret.Add(p);
}
return ret;
}
}
public class Product
{
public int ProductDesc { get; set; }
public string FormingCode { get; set; }
}
}
精彩评论