Archive

Archive for January, 2011

Displaying Image With RequiredFieldValidator

January 22, 2011 Leave a comment

Hi all,

try this example to isplay image with RequiredFieldValidator control :-

Enter User ID :-
<asp:TextBox ID="txtUID" runat="server" />
<asp:RequiredFieldValidator id="txtUIDValidatorReq" runat="server" ControlToValidate="txtUID"
     Display="Dynamic" Text="<img src='../images/icons/error_message.gif' />"
     ErrorMessage="<img src='../images/icons/error_message.gif' /> Please enter a User ID">
</asp:RequiredFieldValidator>

Following image shows the outcome of the above code if the user submits the page without entering the UserID.

Hope this helps

Good Luck

Categories: ASP.Net

Add mailto to a column in a GridView control

January 15, 2011 Leave a comment

Hi all,

try this example to Add mailto to a column in a GridView control

With HyperLink Field

<asp:HyperLinkField DataNavigateUrlFields="Email"
                    DataNavigateUrlFormatString="mailto:{0}"
                    DataTextField="Email" Text="Email me!" />

With HyperLink inside Gridview TemplateField

<asp:TemplateField HeaderText="Email">
   <ItemTemplate>
      <asp:HyperLink ID="emailHyperLink"
                     runat="server"
                     NavigateUrl='<%# Eval("Email", "mailto:{0}") %>'
                     Text='<%# Eval("Email") %>' />
   </ItemTemplate>
</asp:TemplateField>

Hope this helps

Good Luck

Categories: ASP.Net

Generate Random Password with Membership

January 13, 2011 Leave a comment

Hi all

try this example to Generate Random Password with Membership

but First Please Check this link here to show you how to Configure Membership with your Website

now let go to our example :-

<h3>Create New User</h3>
  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>

and in code behind :-


public void CreateUser_OnClick(object sender, EventArgs args)
{
  // Generate a new 12-character password with 1 non-alphanumeric character.
  string password = Membership.GeneratePassword(12, 1);
  try
  {
    // Create new user.
    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, password,EmailTextbox.Text);
    Msg.Text = "User <b>" + Server.HtmlEncode(UsernameTextbox.Text) + "</b> created. " + "Your temporary password is " + password + ".";
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}

public string GetErrorMessage(MembershipCreateStatus status)
{
   switch (status)
   {
      case MembershipCreateStatus.DuplicateUserName:
        return "Username already exists. Please enter a different user name.";

      case MembershipCreateStatus.DuplicateEmail:
        return "A username for that e-mail address already exists. Please enter a different e-mail address.";

      case MembershipCreateStatus.InvalidPassword:
        return "The password provided is invalid. Please enter a valid password value.";

      case MembershipCreateStatus.InvalidEmail:
        return "The e-mail address provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidAnswer:
        return "The password retrieval answer provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidQuestion:
        return "The password retrieval question provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.ProviderError:
        return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      case MembershipCreateStatus.UserRejected:
        return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      default:
        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
   }
}

Hope this helps

Good Luck

Categories: ASP.Net

Merge Repeated Cells in Gridview

January 12, 2011 Leave a comment

Hi all,

Try this example to Merge Repeated Cells in Gridview

1- Open VS and create a new website and add new Web Page and from ToolBox add Gridview Control and Bind it using SQLDayaSource so the page will be like this :-


<div>
    <asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns="False" CellPadding="4" Height="119px" DataSourceID="SqlDataSource1"        
OnDataBound="GridView1_DataBound" ForeColor="#333333">
        <Columns>
            <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
        </Columns>
        <RowStyle BackColor="#EFF3FB" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
       <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT [Country], [State], [City] FROM [Details] ORDER BY [State]"></asp:SqlDataSource>
    </div>

and in code behind we will add some code to Merge repeated cells in Gridview Control

protected void GridView1_DataBound(object sender, EventArgs e)
    {
        for (int rowIndex = GridView1.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow gvRow = GridView1.Rows[rowIndex];
            GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
            for (int cellCount = 0; cellCount < gvRow.Cells.Count; cellCount++)
            {
                if (gvRow.Cells[cellCount].Text == gvPreviousRow.Cells[cellCount].Text)
                {
                    if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
                    {
                        gvRow.Cells[cellCount].RowSpan = 2;
                    }
                    else
                    {
                        gvRow.Cells[cellCount].RowSpan = gvPreviousRow.Cells[cellCount].RowSpan + 1;
                    }
                    gvPreviousRow.Cells[cellCount].Visible = false;
                }
            }
        }
    }

after that run your website and you will see the result will be like the below image

Hope this helps

Good Luck

Categories: ASP.Net

Display Master and Details output with Nested GridView Controls

January 2, 2011 1 comment

Hi try this example to Display Master and Details output with Nested GridView Contro

In this Example i will use Northwind Database .. you can also get it from  here to display Categories and it’s Related Product with Nested Gridview Control

1) Open VS2005 and Create a New Website and Add new Page “Default.aspx” so our page will be like this :-

<asp:GridView ID="MainGridView" runat="server" AutoGenerateColumns="False"
   CellPadding="6" Width="50%" Font-Names="Arial" GridLines="None" BorderColor="#000000"
   BorderStyle="Solid" BorderWidth="1px">
   <Columns>
      <asp:TemplateField HeaderText="Categories and Products">
         <ItemTemplate>
            <asp:Label runat="server" ID="lblCategoryName" Text='<%# Eval("CategoryName") %>'
               Font-Bold="True" Font-Size="12pt" />
            <asp:GridView ID="InnerGridView" runat="server" CellPadding="4" Width="100%"
               DataSource='<%# GetProductsByCategory(Eval("CategoryID").ToString()) %>'
               BorderStyle="Solid" BorderWidth="1px" Font-Size="8pt"
               BorderColor="#336699" GridLines="Horizontal">
               <HeaderStyle BackColor="#336699" Font-Bold="True" ForeColor="White" />
            </asp:GridView>
         </ItemTemplate>
      </asp:TemplateField>
   </Columns>
   <HeaderStyle BackColor="#000000" Font-Bold="True" ForeColor="White" Font-Size="10pt" />
</asp:GridView>

and in Code behind we are going to bind Main Gridview with All Categories and then Bind Inner Gridview with Products related to Each Category so our code will be :-


protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
      LoadCategories();
  }
}

private void LoadCategories()
{
   string constr = @"Server=MyServer;Database=NORTHWND;Integrated Security=True;";
   string query = "SELECT TOP 3 CategoryID, CategoryName FROM Categories";
   SqlDataAdapter da = new SqlDataAdapter(query, constr);
   DataTable table = new DataTable();
   da.Fill(table);
   MainGridView.DataSource = table;
   MainGridView.DataBind();
}

public DataTable GetProductsByCategory(string categoryId)
{
  string constr = @"Server=MyServer;Database=NORTHWND;Integrated Security=True;";
  string query = "SELECT Top 3 ProductID, ProductName, UnitPrice FROM Products WHERE CategoryID = " + categoryId;
  SqlDataAdapter da = new SqlDataAdapter(query, constr);
  DataTable table = new DataTable();
  da.Fill(table);
  return table;
}

Hope this helps

Good Luck and Happy New Year 2011 🙂

Categories: ASP.Net