I would do as below,
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("ddlCompany1");
if(ddl !=null)
{
DataSet ds = GetData("SELECT CompanyName, ID FROM Company");
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "CompanyName";
ddl.DataValueField = "ID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Select", "0"));
}
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand(query,con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
return ds;
}
}
}
Note that,
1. try to separate your UI code and the data access codes
2. Reusable methods
3. you haven't select ID column in your select statement but you set it as value field!
4. Connections handling is not easy when you have class level or global shared connection object, try to use "using blocks" and create the connection when you need and it will close the connection automatically.