Problem binding DropDownList
Am trying to bind data to a dropdown list on pageload based on a condition. Code explains further below.
public partial class AddExhibit : System.Web.UI.Page
{
string adminID, caseIDRetrieved;
DataSet caseDataSet = new DataSet();
SqlDataAdapter caseSqlDataAdapter = new SqlDataAdapter();
string strConn = WebConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
adminID = Request.QueryString["adminID"];
caseIDRetrieved = Request.QueryString["caseID"];
if (caseIDRetrieved != null)
开发者_如何转开发 {
CaseIDDropDownList.Text = caseIDRetrieved;
//CaseIDDropDownList.Enabled = false;
}
else
{
try
{
CreateDataSet();
DataView caseDataView = new DataView(caseDataSet.Tables[0]);
CaseIDDropDownList.DataSource = caseDataView;
CaseIDDropDownList.DataBind();
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
}
The CreateDataset method that is called in the if..else statement is contains the following code.
private void CreateDataSet()
{
SqlConnection caseConnection = new SqlConnection(strConn);
caseSqlDataAdapter.SelectCommand = new SqlCommand("Select CaseID FROM Cases", caseConnection);
caseSqlDataAdapter.Fill(caseDataSet);
}
However when I load the page and as usual the condition that is supposed to bid the data is met, the gridview decides to displays as follows...
IS IT ME OR ITS THE DATAGRID?...??
You are trying to bind a combo box to a Data View. You're not a dumb, but it's definitely your fault!!
The problem behind this is that what you bind (DataView
) is a collection of DataRowView
, which is a multi-dimensional entity (ie. a table) when combo boxes are unidimensional.
The reason why you get this is that combo boxes use the ToString()
method to render the object they are bound to. So, making it all together, you are binding the combo box to a collection of rows, each element of combo box is bound to a row, which is not an entity that can be rendered as a string (as it contains more columns in general, even if in your case you have one column).
Solution 1 (bad, requires little more coding and processing)
Transform the DataView in a IEnumerable<string>
, you'll get it rendered immediately!
Solution 2 (good)
Acting on the combo box, set the DataTextField
property to CaseID
I wanted to tell you about both solutions
Firstly, that isn't a DataGridView. Secondly, you need to set its DataTextField property.
You need to set DataTextField property of your ComboBox.
精彩评论