适用环境:Winform开发,VS2008开发工具
问题描述:
cboxProduct.DisplayMember = "ProductName";
cboxProduct.ValueMember = "ProductId";
cboxProduct.DataSource = dataTable; //Product Data Source
4. 要能够根据产品信息,自动选择到特定产品。
解决思路:
下面我们来看一个实际的例子实现吧!
实例代码:
class ProductType<T, TK>
{
public ProductType(T value, TK text)
{
_value = value;
_text = text;
}
private T _value;
/// <summary>
/// 值
/// </summary>
public T Value
{
get { return _value; }
set { _value = value; }
}
private TK _text;
/// <summary>
/// 显示值
/// </summary>
public TK Text
{
get { return _text; }
set { _text = value; }
}
public override string ToString()
{
return _text.ToString();
}
public override bool Equals(object obj)
{
return ((ProductType<T, TK>)obj).Value.Equals(_value);
}
}
private void BindingProductType(int parentProductTypeId, string splitStr)
{
var dataSource = bllProductType.GetList(" parentId=" + parentProductTypeId).Tables[0];
foreach (DataRow dataRow in dataSource.Rows)
{
var productTypeId = Convert.ToInt32(dataRow["productTypeId"]);
cboxProductType.Items.Add(new ProductType()<int, string>(productTypeId,
splitStr + dataRow["productTypeName"]));
BindingProductType(productTypeId, splitStr + @"--|");
}
}
ProductType<int, string> productType = new ProductType(productTypeId, "");
cboxProductType.SelectedItem = productType;
由于产品类型ID是唯一值,我们在产品类型类中比较时也只与Value值相关,因此在实例化ProductType类时,无须提供Text属性值,因为Text属性值对于我们判断产品类型是否相等无关。(这种情况主要使用在编辑数据时,根据已有数据进行填充和选择。)