Archive for » December, 2008 «

Wednesday, December 24th, 2008 | Author: admin
string emailRegex = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (!System.Text.RegularExpressions.Regex.IsMatch(email, emailRegex) && email.Length > 0)
        {
            error.Append("<li>Please enter a valid EMAIL address</li>");
            txtEmail.CssClass = "txtboxError";
        }
        else
        {
            txtEmail.CssClass = "formtextbox";
        }

Wednesday, December 24th, 2008 | Author: admin

The ASPX page code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnPageIndexChanging="GridView1_PageIndexChanging"
        AllowSorting="True" OnSorting="GridView1_Sorting" EmptyDataText="No records found"
        PagerSettings-Mode="NumericFirstLast" PagerSettings-Position="TopAndBottom" PagerSettings-FirstPageText="first page"
        PagerSettings-LastPageText="last page" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:BoundField DataField="adminID" HeaderText="ID" ItemStyle-HorizontalAlign="Center"
                ItemStyle-CssClass="generic_gridview_hidecolumn" HeaderStyle-CssClass="generic_gridview_hidecolumn" />
            <asp:HyperLinkField DataNavigateUrlFields="adminID" DataNavigateUrlFormatString="user-details.aspx?ID={0}"
                DataTextField="UserName" Text="UserName" HeaderText="Username" SortExpression="UserName" />
            <asp:BoundField DataField="fullname" HeaderText="Full Name" ItemStyle-HorizontalAlign="Center"
                SortExpression="fullname" />
            <asp:TemplateField>
                <HeaderTemplate>
                    Active
                </HeaderTemplate>
                <ItemTemplate>
                    <div class="textalignCenter">
                        <asp:CheckBox ID="chkActive" runat="server" AutoPostBack="true" OnCheckedChanged="chkActive_CheckChanged" />
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <HeaderTemplate>
                    Admin
                </HeaderTemplate>
                <ItemTemplate>
                    <div class="textalignCenter">
                        <asp:CheckBox ID="chkAdmin" runat="server" AutoPostBack="true" OnCheckedChanged="chkAdmin_CheckChanged" />
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:HyperLinkField DataNavigateUrlFields="adminID" DataNavigateUrlFormatString="user-resetpassword.aspx?ID={0}"
                Text="RESET PASSWORD" HeaderText="" ItemStyle-HorizontalAlign="Center" />
        </Columns>
    </asp:GridView>

 

 

The Code Behind

public SortDirection SortDir
    {
        get
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = SortDirection.Ascending;
            } return (SortDirection)ViewState["sortDirection"];
        }
        set
        {
            ViewState["sortDirection"] = value;
        }
    }

    DataSet ds = new DataSet();
    DataView dv = new DataView();
    SqlConnection conn = new SqlConnection();
    SqlDataAdapter da = new SqlDataAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //hide the notification panels
            PanelNotice.Visible = false;
            PanelError.Visible = false;
            PanelSuccess.Visible = false;
            //bind the data to the grid
            BindGrid();
            GridView1.DataSource = dv;
            GridView1.DataBind();
        }

    }

    private DataView BindGrid()
    {
        string adminDD = ddAdmin.SelectedValue.ToString();
        string activeDD = ddActive.SelectedValue.ToString();

        //Generate the SQL
        StringBuilder SQL = new StringBuilder();
        SQL.Append(" SELECT firstname + ' ' + Lastname AS fullname,");
        SQL.Append(" adminID, Enabled, Admin, Username");
        SQL.Append(" FROM admin_users");
        SQL.Append(" WHERE Username <> 'admin'");

        //Do I need to filter the results??
        // ADMIN FILTER
        if (adminDD != "Admin...")
        {
            SQL.Append(" AND admin = '" + adminDD + "'");
        }
        // ACTIVE FILTER
        if (activeDD != "Active...")
        {
            SQL.Append(" AND enabled = '" + activeDD + "'");
        }

        SQL.Append(" ORDER BY userName");

        //Initialize connection
        conn = new SqlConnection(connectionString);

        da = new SqlDataAdapter(SQL.ToString(), conn);
        da.Fill(ds);

        string recordCount = ds.Tables[0].Rows.Count.ToString();
        lblRecordCount.Text = "Records Found:<b>" + recordCount + "</b>";

        if (ViewState["sortExpr"] != null)
        {
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortExpr"];

        }
        else
        {
            dv = ds.Tables[0].DefaultView;
        }

        GridView1.PageSize = Convert.ToInt32(ddResultsPerPage.SelectedValue);

        return dv;
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selectedRowIndex;
        selectedRowIndex = GridView1.SelectedIndex;
        GridViewRow row = GridView1.Rows[selectedRowIndex];
        string ID = row.Cells[0].Text;

        Response.Redirect("customer-details.aspx?ID=" + ID, false);
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string stExp = e.SortExpression;
        string stDir = string.Empty;
        if (SortDir == SortDirection.Ascending)
        {
            SortDir = SortDirection.Descending;
            stDir = "DESC";
        }
        else
        {
            SortDir = SortDirection.Ascending;
            stDir = "ASC";
        }

        ViewState["sortExpr"] = e.SortExpression + " " + stDir;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // get the "Active" value
            string userID = e.Row.Cells[0].Text;
            bool userActive = Convert.ToBoolean(CommonDBCommands.SelectValue(connectionString, "admin_users", "enabled", "adminID", userID));
            bool userAdmin = Convert.ToBoolean(CommonDBCommands.SelectValue(connectionString, "admin_users", "admin", "adminID", userID));
            if (userActive)
            {
                ((CheckBox)e.Row.Cells[3].FindControl("chkActive")).Checked = true;
            }
            else
            {
                ((CheckBox)e.Row.Cells[3].FindControl("chkActive")).Checked = false;
            }
            if (userAdmin)
            {
                ((CheckBox)e.Row.Cells[4].FindControl("chkAdmin")).Checked = true;
            }
            else
            {
                ((CheckBox)e.Row.Cells[4].FindControl("chkAdmin")).Checked = false;
            }
        }
    }

    protected void ddResultsPerPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    protected void chkActive_CheckChanged(object sender, EventArgs e)
    {
        //Clear Selection
        GridView1.SelectedIndex = -1;

        // Get the checkbox that was Selected
        CheckBox selectedCheckbox = (CheckBox)sender;

        // As this is a template column, we can get the specifc row by using the Naming Container
        GridViewRow selectedGridRow = (GridViewRow)selectedCheckbox.NamingContainer;

        // get the userID from the first column that is hidden by CSS
        string userID = selectedGridRow.Cells[0].Text;

        // get the value of the checkbox
        CheckBox chk = (CheckBox)selectedGridRow.Cells[3].FindControl("chkActive");
        bool userActive;
        if (chk.Checked)
        {
            userActive = true;
        }
        else
        {
            userActive = false;
        }

        //update the record
        try
        {
            CommonDBCommands.UpdateRowSingleField(connectionString, "admin_users", "enabled", userActive.ToString(), "adminID", userID);
        }
        catch (Exception ex)
        {
            PanelError.Visible = true;
            lblError.Text = ex.Message.ToString();
        }
    }

    protected void chkAdmin_CheckChanged(object sender, EventArgs e)
    {
        // Get the checkbox that was Selected
        CheckBox selectedCheckbox = (CheckBox)sender;

        // As this is a template column, we can get the specifc row by using the Naming Container
        GridViewRow selectedGridRow = (GridViewRow)selectedCheckbox.NamingContainer;

        // get the userID from the first column that is hidden by CSS
        string userID = selectedGridRow.Cells[0].Text;

        // get the value of the checkbox
        CheckBox chk = (CheckBox)selectedGridRow.Cells[3].FindControl("chkActive");
        bool userAdmin;
        if (chk.Checked)
        {
            userAdmin = true;
        }
        else
        {
            userAdmin = false;
        }

        //update the record
        try
        {
            CommonDBCommands.UpdateRowSingleField(connectionString, "admin_users", "admin", userAdmin.ToString(), "adminID", userID);
        }
        catch (Exception ex)
        {
            PanelError.Visible = true;
            lblError.Text = ex.Message.ToString();
        }
    }

    protected void ddAdmin_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    protected void ddActive_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    protected void btnClearFilters_Click(object sender, EventArgs e)
    {
        ddActive.SelectedIndex = 0;
        ddAdmin.SelectedIndex = 0;

        BindGrid();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

Category: ASP.NET, C#  | Leave a Comment
Wednesday, December 17th, 2008 | Author: admin
DropDownList ddDynamic;
        int iTextCount = 0;

        try
        {
            for (iTextCount < 10; iTextCount++)
            {
                ddDynamic = new DropDownList();
                ddDynamic.ID = "ddDynamic_" + iTextCount;
                ddDynamic.Items.Add("Hello World");

                Panel1.Controls.Add(ddDynamic);
            }

        }
        catch(Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }

Category: ASP.NET, C#  | Leave a Comment
Monday, December 15th, 2008 | Author: admin

ASPX page

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnPageIndexChanging="GridView1_PageIndexChanging"
        AllowSorting="True" OnSorting="GridView1_Sorting" EmptyDataText="No records found" PageSize="10"
        PagerSettings-Mode="NumericFirstLast">
        <Columns>
            <asp:BoundField DataField="clnID" HeaderText="ID" ItemStyle-CssClass="generic_gridview_hidecolumn"
                HeaderStyle-CssClass="generic_gridview_hidecolumn" >
<HeaderStyle CssClass="generic_gridview_hidecolumn"></HeaderStyle>

<ItemStyle CssClass="generic_gridview_hidecolumn"></ItemStyle>
            </asp:BoundField>
            <asp:HyperLinkField DataNavigateUrlFields="clnID" DataNavigateUrlFormatString="customer-details.aspx?ID={0}"
                DataTextField="clnLastName" Text="&nbsp;Name" HeaderText="&nbsp;Name" SortExpression="clnLastName"/>
            <asp:BoundField DataField="clnAddress1" HeaderText="Address" SortExpression="clnAddress1" />
            <asp:BoundField DataField="clnCity" HeaderText="City" SortExpression="clnCity" />
            <asp:BoundField DataField="clnPhone" HeaderText="Phone" SortExpression="clnPhone"/>
        </Columns>
    </asp:GridView>

CODE BEHIND page

 

public partial class application_customers_customer_list : System.Web.UI.Page
{
    //read the connection string from web.config
    public static string connectionString = ConfigurationManager.ConnectionStrings[
        "CartConnectionString"].ConnectionString;

    public SortDirection SortDir
    {
        get
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = SortDirection.Ascending;
            } return (SortDirection)ViewState["sortDirection"];
        }
        set
        {
            ViewState["sortDirection"] = value;
        }
    }

    DataSet ds = new DataSet();
    DataView dv = new DataView();
    SqlConnection conn = new SqlConnection();
    SqlDataAdapter da = new SqlDataAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
            GridView1.DataSource = dv;
            GridView1.DataBind();
        }
    }

    private DataView BindGrid()
    {
        //Generate the SQL
        StringBuilder SQL = new StringBuilder();
        SQL.Append(" SELECT *");
        SQL.Append(" FROM client");

        string searchTxt = txtSearch.Text;

        // Has the user searched for anything?
        if (searchTxt.Length > 0)
        {
            SQL.Append(" WHERE clnLastName LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnAddress1 LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnCity LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnPhone LIKE '%" + searchTxt + "%' ");
        }

        //Initialize connection
        conn = new SqlConnection(connectionString);

        da = new SqlDataAdapter(SQL.ToString(), conn);
        da.Fill(ds);

        if (ViewState["sortExpr"] != null)
        {
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortExpr"];
        }
        else
        {
            dv = ds.Tables[0].DefaultView;
        }

        return dv;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string stExp = e.SortExpression;
        string stDir = string.Empty;
        if (SortDir == SortDirection.Ascending)
        {
            SortDir = SortDirection.Descending;
            stDir = "DESC";
        }
        else
        {
            SortDir = SortDirection.Ascending;
            stDir = "ASC";
        }

        ViewState["sortExpr"] = e.SortExpression + " " + stDir;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selectedRowIndex;
        selectedRowIndex = GridView1.SelectedIndex;
        GridViewRow row = GridView1.Rows[selectedRowIndex];
        string ID = row.Cells[0].Text;

        Response.Redirect("customer-details.aspx?ID=" + ID, false);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

}
Category: ASP.NET, C#  | Leave a Comment