ASP.NET control in GridView not found to exist in code behind

前端 未结 3 1538
梦毁少年i
梦毁少年i 2021-01-28 12:08

I have a DropDownList that I would like to populate with column values from a DataBase. However, when I try to bind the DropDownList in code behind, the IDE keeps telling me:

相关标签:
3条回答
  • 2021-01-28 12:41

    Use this code to bound data to dropdown without using RowDataBound.

    Create a function that'll bind the Data to dropdown as follow and call it in Page_Load event

    Public void fill_gridView_dropDown()
    {
        // your connection and query to retrieve dropdown data will go here 
        // this loop will go through all row in GridView
        foreach(GridViewRow row in your_gridView_Name.Rows) {
            DropDownList  dropDown = (DropDownList)row.FindControl("dropDownList_id");
            dropDown.DataSource = dataSource;
            dropDown.DataValueField = "ValueField";
            dropDown.DataTextField = "TextField";
            dropDown.DataBind();
        }
    }
    

    Please note that you have to bind GridView first, and then you have to bind your dropdown

    0 讨论(0)
  • 2021-01-28 12:42

    your dropdown is in gridview so you can try with this code

    protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var ddl = (DropDownList)e.Row.FindControl("EqpCatDDL'");
        SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection);
    
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
    
        EqpCatDDL.DataSource = ds;
        EqpCatDDL.DataValueField = "EqpCateID";
        EqpCatDDL.DataTextField = "EqpCat";
        EqpCatDDL.DataBind();
    
    }
    }
    
    0 讨论(0)
  • 2021-01-28 13:06

    You can't directly populate GridView's dropdownlist like this. You need to set datasource of GridView first i.e.

    GridView1.DataSource = DataSource
    

    And if you would like to access dropdownlist of this gridview, you can use RowDataBound event handler of GridView i.e.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //Checking whether the Row is Data Row
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Finding the Dropdown control.
            Control ctrl = e.Row.FindControl("EqpCatDDL");
            if (ctrl != null)
            {
                DropDownList dd = ctrl as DropDownList;
                List lst = new List();
                dd.DataSource = lst;
                dd.DataBind();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题