txtSubject.BackColor = ColorTranslator.FromHtml("#C4C4C4");
Monday, February 09th, 2009 | Author: admin
Category: ASP.NET, C#
| Leave a Comment
Friday, January 30th, 2009 | Author: admin
The aspx page
<asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="btnTemplate" runat="server" OnClick="btnTemplate_Click">LinkButton</asp:LinkButton> </ItemTemplate> </asp:TemplateField>
The C# code behind
protected void btnTemplate_Click(object sender, EventArgs e) { //Clear Selection GridView1.SelectedIndex = -1; // Get the checkbox that was Selected LinkButton btnTemplate = (LinkButton)sender; // As this is a template column, we can get the specifc row by using the Naming Container GridViewRow selectedGridRow = (GridViewRow)btnTemplate.NamingContainer; // get the userID from the first column that is hidden by CSS Response.Write(selectedGridRow.Cells[0].Text); }
Category: ASP.NET, C#
| Leave a Comment
Tuesday, January 13th, 2009 | Author: admin
Category: ASP.NET, C#
| Leave a Comment
Friday, January 02nd, 2009 | Author: admin
//set the drop down list values
if (ddAccounts.Items.FindByValue(cb.parentAccountID.ToString()) != null)
{
ddAccounts.Items.FindByValue(cb.parentAccountID.ToString()).Selected = true;
}
if (ddAccounts.Items.FindByValue(cb.parentAccountID.ToString()) != null)
{
ddAccounts.Items.FindByValue(cb.parentAccountID.ToString()).Selected = true;
}
Category: ASP.NET, C#
| Leave a Comment
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"; }
Category: ASP.NET, C#, Validation
| Leave a Comment
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=" Name" HeaderText=" 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
Wednesday, November 26th, 2008 | Author: admin
namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { public String connectionString = ConfigurationManager.ConnectionStrings[ "DefaultDatabase"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { string contentID = ""; contentID = (string)Request.QueryString["ID"]; if (contentID != "" && contentID != null) { LoadControl(); } //ph.Controls.Add(new AnthemText.TextAndImage()); } protected void LoadControl() { string contentID = Request.QueryString["ID"]; string layoutID = CommonDBCommands.SelectValue(connectionString, "txtContent", "cntLayoutID", "cntID", Request.QueryString["ID"]); string customControl = CommonDBCommands.SelectValue(connectionString, "txtLayout", "layCustomControl", "layID", layoutID); string controlReference = CommonDBCommands.SelectValue(connectionString, "txtLayout", "layReference", "layID", layoutID); //System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(@"C:\Users\mlecount\Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\bin\App_Web_textandimage.ascx.3910acf1.dll"); System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(Server.MapPath("~/bin/" + controlReference)); object obj = asm.CreateInstance("AnthemText." + customControl); if (obj is UserControl) { UserControl uc = (UserControl)obj; ph.Controls.Add(uc); } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("~/Default.aspx?ID=" + txtContentID.Text, false); } } }
Category: ASP.NET, C#
| Leave a Comment
Saturday, November 22nd, 2008 | Author: admin
The Stored Procedure
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Marcus Le Count> -- Create date: <22 November 2008> -- Description: <Inserts a new record into the Accounts Table> -- ============================================= ALTER PROCEDURE [dbo].[CreateNewAccount] ( @AccountName nvarchar(50), @OpeningBalance money, @Balance money, @DateCreated datetime, @LastUpdate datetime, @AccountType int, @CreatedBy int ) AS DECLARE @MyIdentity int BEGIN INSERT INTO [accounts] ([accountName] ,[balance] ,[openingBalance] ,[dateCreated] ,[dateLastUpdate] ,[accountType] ,[createdBy]) VALUES (@AccountName ,@Balance ,@OpeningBalance ,@DateCreated ,@LastUpdate ,@AccountType ,@CreatedBy) SELECT @MyIdentity = SCOPE_IDENTITY() SELECT @MyIdentity AS [MyIdentity] RETURN END
The ASP.NET code
public String CreateNewAccount() { SqlConnection conn; SqlCommand comm; string newID; //read the connection string from web.config string connectionString = ConfigurationManager.ConnectionStrings[ "DefaultDatabase"].ConnectionString; //Initialize connection conn = new SqlConnection(connectionString); //create command (using stored Procedure) comm = new SqlCommand("CreateNewAccount", conn); comm.CommandType = CommandType.StoredProcedure; //add the command parameters comm.Parameters.AddWithValue("@AccountName", System.Data.SqlDbType.NVarChar); comm.Parameters["@AccountName"].Value = m_AccountName; comm.Parameters.AddWithValue("@OpeningBalance", System.Data.SqlDbType.Money); comm.Parameters["@OpeningBalance"].Value = m_OpeningBalance; comm.Parameters.AddWithValue("@Balance", System.Data.SqlDbType.Money); comm.Parameters["@Balance"].Value = m_Balance; comm.Parameters.AddWithValue("@DateCreated", System.Data.SqlDbType.DateTime); comm.Parameters["@DateCreated"].Value = m_DateCreated; comm.Parameters.AddWithValue("@LastUpdate", System.Data.SqlDbType.DateTime); comm.Parameters["@LastUpdate"].Value = m_LastUpdate; comm.Parameters.AddWithValue("@AccountType", System.Data.SqlDbType.Int); comm.Parameters["@AccountType"].Value = m_AccountType; comm.Parameters.AddWithValue("@CreatedBy", System.Data.SqlDbType.Int); comm.Parameters["@CreatedBy"].Value = m_CreatedBy; try { //open the connection conn.Open(); //execute the command newID = Convert.ToString(comm.ExecuteScalar()); return newID; } catch { return "false"; } finally { //close the connection conn.Close(); comm.Dispose(); } }
Category: ASP.NET, C#, SQL, Stored Procedures
| Leave a Comment
