Hi osupratt,
No need to copy the code again and again. Need to create a common method with parameter and call the method when ever required like below.
The PopulateDropDownList method is the common function. You just need to pass the DoroDownList ID, DataTextField, DataValueField and SQL Query as parameters. So whenever you want to populate DropDownList then call the method with those parameters.
For this you need to write like below.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
PopulateDropDownList(ddlLeaseWell, "LeaseNameWellNo", "ID", "SELECT LeaseNameWellNo, ID FROM LeaseNameWellNo");
}
}
private void PopulateDropDownList(DropDownList ddl, string dataTextField, string dataValueField, string query)
{
string constr = ConfigurationManager.ConnectionStrings["LESFieldTicketConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
ddl.DataTextField = dataTextField;
ddl.DataValueField = dataValueField;
ddl.DataSource = ds;
ddl.DataBind();
ddl.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Please Select", "0"));
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
PopulateDropDownList(ddlLeaseWell, "LeaseNameWellNo", "ID", "SELECT LeaseNameWellNo, ID FROM LeaseNameWellNo")
End If
End Sub
Private Sub PopulateDropDownList(ddl As DropDownList, dataTextField As String, dataValueField As String, query As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("LESFieldTicketConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
Using da As New SqlDataAdapter(cmd)
con.Open()
Dim ds As New DataSet()
da.Fill(ds)
ddl.DataTextField = dataTextField
ddl.DataValueField = dataValueField
ddl.DataSource = ds
ddl.DataBind()
ddl.Items.Insert(0, New System.Web.UI.WebControls.ListItem("Please Select", "0"))
End Using
End Using
End Using
End Sub