Author Topic: Binding From CodeBehind  (Read 5109 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Binding From CodeBehind
« on: May 12, 2009, 09:17:38 PM »
Binding From CodeBehind

ASPX
Code: [Select]
<asp:DropDownList ID="ddlRoles" runat="server" Width="10em">

                </asp:DropDownList>
CodeBehind

Code: [Select]
protected void Page_Load(object sender, EventArgs e)

    {   

        if (!IsPostBack)

        {

         ddlRoles.DataSource = GetAllRoles();

         ddlRoles.DataValueField = "RoleID";

         ddlRoles.DataTextField = "Role";

         ddlRoles.DataBind();

         ddlRoles.Items.Insert(0, new ListItem("Select",""));

        }

    }

 

public DataTable GetAllRoles()

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand("SP_GetAllRoles", con);

        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ada = new SqlDataAdapter(com);

        DataTable dt = new DataTable();

        ada.Fill(dt);

        return dt;

    }


In the above code, I have given the database column name "RoleID" that should be populated for value field of ListItem. Similarly, Role for text field.

 

Binding from ASPX page
We can also bind the dropdownlist from ASPX page by calling function GetAllRoles(). The only constraint is we should make the function as public to access it from ASPX page.

 

 ASPX

Code: [Select]
<asp:DropDownList ID="ddlRoles" DataSource='<%# GetAllRoles() %>'

                                DataTextField="Role"  DataValueField="RoleID"

                                SelectedValue='<%# Bind("RoleID") %>' runat="server">

                                </asp:DropDownList>

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
Using Method inside a DataGrid or GridView TemplateField
« Reply #1 on: May 12, 2009, 09:20:30 PM »
GridView Example:

Code: [Select]
<asp:TemplateField HeaderText=”Name”>
    <ItemTemplate>
        <a href=’<%# FormatUrl(Eval(”email1″).ToString())%>’><%# Eval(”fname”) %>,&nbsp;<%# Eval(”lname”) %></a>
    </ItemTemplate>
</asp:TemplateField>

As you can see, I am calling a method called FormatUrl with an input the email field we’re getting from the database.

DataGrid Example:

Code: [Select]
<asp:TemplateColumn HeaderText=”Name”>
    <ItemTemplate>
        <a href=’<%# FormatUrl(Eval(”email1″).ToString())%>’><%# Eval(”fname”) %>,&nbsp;<%# Eval(”lname”) %></a>
    </ItemTemplate>
</asp:TemplateColumn>
Now the FormatUrl method is as simple as the following:

Code: [Select]
public string FormatUrl(string email)
{
    return “mailto:” + email;
}