I have a gridview that is linked to a datasource. I have a column called patched_date.

How do I highlight that column where the date is older than 30 days, 60 days, etc.

I'm not a coder. I did find somethings similar, but I dont understand it. Is there a different code that I can use?

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    for (int i = 0; i < GridView2.Rows.Count; i++)
    {
        DateTime date_patched = Convert.ToDateTime(GridView2.Rows[i].Cells[3].Text);
        if (date_patched < DateTime.Now)
        {
            GridView2.Rows[i].Cells[3].BackColor = System.Drawing.Color.Red;
        }

    }

I am populating a grid in asp with results from a database table called Students. The students table has columns of pointsEarned and pointsPossible. I need to calculate the letter grade based on the percentage of pointsEarned / pointsPossible. I do this in a class called Grades. How do I get the values of pointsEarned and pointsPossible for the current student and then add the calculated letterGrade to the grid?

Here's my method:

 protected void Page_Load(object sender, EventArgs e)
        {
            string connstring;
            connstring = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
            SqlConnection conn = new SqlConnection(connstring);
            SqlCommand cmd = new SqlCommand("GetStudents", conn);

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            conn.Open();

            DataSet ds = new DataSet();
            adapter.Fill(ds, "dbo.Students");
            DataTable dt = new DataTable();
            dt.Columns.Add("letterGrade", typeof(string));

            Grades studentGrade = new Grades();
            studentGrade.pointsEarned = ???;
            studentGrade.pointsPossible = ???;
            string studentLetterGrade = studentGrade.calculate();

            //How do I add studentLetterGrade as the letterGrade column?

            StudentGrid.DataSource = ds;
            StudentGrid.DataBind();

            conn.Close();
            conn.Dispose();
        }

Here's my grid:

<asp:SqlDataSource ID="GetStudents" runat="server" ConnectionString="<%$ ConnectionStrings:dbConn %>" SelectCommand="dbo.GetStudents" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
        <asp:GridView ID="StudentGrid" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:CommandField ShowSelectButton="False" />
                <asp:BoundField DataField="studentId" HeaderText="ID" />
                <asp:BoundField DataField="firstName" HeaderText="First Name" />
                <asp:BoundField DataField="lastName" HeaderText="Last Name" />
                <asp:BoundField DataField="semester" HeaderText="Semester" />
                <asp:BoundField DataField="semesterYear" HeaderText="Year" />
                <asp:BoundField DataField="letterGrade" HeaderText="Grade" />
            </Columns>
        </asp:GridView>

I am having an issue with a piece of code that is referenced when a button on my website is clicked. If I remove its reference from the btn_Click event, the error is not triggered (because its not being called) so I am sure the error is located within the below code so I haven't included everything as there is a lot. The error I recieve when clicking on the button is as follows:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: Input string was not in a correct format.

The error points to this line of code from the below code block:

    long ProductPrice = Convert.ToInt64(PriceLabel.Text) * Convert.ToInt64(BasketQuantity.Text);

Update Total Bill

    private void UpdateTotalBill()
    {
        long NumberOfProductsInBasket = 0;
        long SumOfBasket = 0;

        foreach (DataListItem item in dlBasketItems.Items)
        {
            Label PriceLabel = item.FindControl("lblProductPrice") as Label;
            TextBox BasketQuantity = item.FindControl("txtBasketQuantity") as TextBox;
            long ProductPrice = Convert.ToInt64(PriceLabel.Text) * Convert.ToInt64(BasketQuantity.Text);
            NumberOfProductsInBasket = NumberOfProductsInBasket + Convert.ToInt32(BasketQuantity.Text);
            SumOfBasket = SumOfBasket + ProductPrice;
        }
        txtNumberOfProductsInBasket.Text = Convert.ToString(NumberOfProductsInBasket);
        txtSumOfBasket.Text = Convert.ToString(SumOfBasket);
    }

I have included the PnlBasket code as well for reference:

        <asp:Panel ID="pnlBasket" runat="server" ScrollBars="Auto" Height="730px" BorderColor="Black"
                                        BorderStyle="Inset" BorderWidth="1px" Visible="false">
                                        <table align="center" cellspacing="1">
                                            <tr>
                                                <td align="center">
                                                    <asp:Label ID="lblProductStock" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
                                                    <asp:DataList ID="dlBasketItems" runat="server" RepeatColumns="3" Font-Bold="false"
                                                        Font-Italic="false" Font-Overline="false" Font-Strikeout="false" Font-Underline="false"
                                                        width="600px">
                                                        <ItemTemplate>
                                                            <div align="left">
                                                                <table cellspacing="1" style="border: 1px ridge #9900FF; text-align: center; width: 170px;">
                                                                    <tr>
                                                                       <td style="border-bottom-style: ridge; border-width: 1px; border-color: #000000">
                                                                            <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName")%>' Style="font-weight: 700"></asp:Label>
                                                                        </td>
                                                                    </tr>
                                                                    <tr>
                                                            <td>
                                                                <img alt="" src='<%# Eval ("ProductImageUrl") %>' runat="server" id="imgProductImage" style="border: ridge 1px black; width: 173px; height: 160px;" />
                                                            </td>
                                                            </tr>

                                                            <tr>
                                                                <td>
                                                                    Stock Avaliability:&nbsp;
                                                                    <asp:Label ID="lblAvailableStock" runat="server" Text='<%# Eval ("AvailableStock") %>'
                                                                        ToolTip="Currently In Stock" ForeColor="Red" Font-Bold="true"></asp:Label>
                                                                </td>
                                                            </tr>

                                                             <tr>
                                                             <td>
                                                                Price:<asp:Label ID="lblProductPrice" runat="server" Text='<%# Eval ("ProductPrice") %>'></asp:Label>
                                                                &nbsp; Basket Quantity x&nbsp;
                                                                <asp:TextBox ID="txtBasketQuantity" runat="server" Width="15px" Height="15px" MaxLength="2"
                                                                    OnTextChanged="txtBasketQuantity_TextChanged" AutoPostBack="true" Text='<%# Eval ("ProductStock")%>'></asp:TextBox>
                                                                <asp:HiddenField ID="hfProductID" runat="server" Value='<%# Eval ("ProductID") %>' />
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>
                                                                <hr />
                                                                <asp:Button ID="btnRemoveFromBasket" runat="server" CommandArgument= '<%# Eval ("ProductID") %>'
                                                                    Text="Remove From Basket" Width="100%" BorderColor="Black" BorderStyle="Inset" BorderWidth="1px"
                                                                     CausesValidation="false" />
                                                            </td>
                                                        </tr>
                                                    </table>
                                                   </div>
                                                  </ItemTemplate>
                                                 <ItemStyle Width="33%" />
                                             </asp:DataList>

Is there a blindingly obvious mistake I have made (I'm sure there is given I am coding! ha!)? Thanks as ever for any pointers in the right direction. Jack

I have the following code and I need to declare the Javascript variable as shown below but Razor syntax is coming in the way.

  @foreach (var arrivalDateTimeViewModel in Model.ArrivalDateViewModels.Take(7))
    { 
          <script>
            var m = Html.Raw(Json.Encode(arrivalDateTimeViewModel));
          </script>

            <td>

How can I do that?

I just noticed a strange behaviour which I am not quite sure about . I am pretty new to jQuery and AJAX. So might just well be missing some basics.

In my MVC rzaor view there are some AJAX Action links which when clicked render a partial view containing the Student Details in the div #StudentDetails.

    <div id="mainpage">

    <h2>Registration Details</h2>
    <ul>
    @foreach(var item in Model) 
    {
        <li>
            @Ajax.ActionLink(item.Student.UserName, @*Text to be displayed *@
            "GetUserDetails", @*Action Method Name*@
            new { id = item.Student.StudentId },
                new AjaxOptions
                {
                    UpdateTargetId = "StudentDetails", @*DOM element ID to be updated *@
                    InsertionMode = InsertionMode.Replace,@*Replace the content of DOM element *@
                    HttpMethod = "GET" @*HTTP method *@,
                    OnComplete="RegisterClickHanders"
                }
            )
        </li>
    }
    </ul>
    <div id ="StudentDetails"></div>
    <br />
    <div id ="Add_Update_Details"></div>
</div>

After the view gets rendered with the details, Edit or Add buttons can be clicked and the appropriate partial views get rendered. enter image description here

<script>
//Event Delegation
//$(function () {
//One can also use Event Delegation as stated above to handle dynamically added elements i.e. the elements
//that are added after the page is first loaded.
function RegisterClickHanders() {

    var url = '@Url.Action("DisplayClickedView","Private")'; // Name of the action method you want to call and the name of the 
    //controller the action method resides
            $('.editDetails').click(function () {
                var btnvalue = $('.editDetails').attr("value");
                var studentId = $('.editDetails').data("student-id");

                        $('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: studentId });
            });

            $('.addDetails').click(function () {
                var btnvalue = $('.addDetails').attr("value");

                $('#Add_Update_Details').load(url, { searchText: btnvalue });
            });

}
</script>

In my controller when I put my breakpoints : enter image description here

they get hit exactly once which is intended. But when I replace the ajax calls as :

        $('.editDetails').click(function () {
        var btnvalue = $('.editDetails').attr("value");
        var studentId = $('.editDetails').data("student-id");

        $.ajax({
            type: 'POST',
            url: url,
            data: { searchText: btnvalue, searchValue: studentId },
            success: function () {
                $('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: studentId });
            },
            error: function (jqXHR, status, err) {//status is Error and the errorThrown is undefined
                alert('Request Status : ' + jqXHR.status + ' has issued a status text of  : ' + jqXHR.statusText);
            }
        });
    });



    $('.addDetails').click(function () {
        var btnvalue = $('.addDetails').attr("value");

        $.ajax({
            type: 'POST',
            url: url,
            data: { searchText: btnvalue },
            success: function () {
                $('#Add_Update_Details').load(url, { searchText: btnvalue });
            },
            error: function (jqXHR, status, err) {//status is Error and the errorThrown is undefined
                alert('Request Status : ' + jqXHR.status + ' has issued a status text of  : ' + jqXHR.statusText);
            }
        });

    });

The breakpoints in the controller get hit twice upon pressing any of the buttons . What am I missing ? Or is this intended ? Is AJAX call causing a performance hit ?

I am trying to display both: Validated form and a database table on the same page. Code is below:

Create Controller

 public ActionResult Create()
    {

        return View(db.Donations.OrderByDescending(x=> x.ID).Take(5).ToList());  //Display 5 recent records from table 
    }

    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,DisplayName,Date,Amount,TaxBonus,Comment")] Charity charity)
    {

        if (ModelState.IsValid)
        {
            db.Donations.Add(charity);
            db.SaveChanges();
            return RedirectToAction("AdditionalInfo");
        }
        return View(charity);
    }

Since the form is automatically created I though to set it as a Partial View and use it in the "Create" view.

Partial View(_Form) Model

   @model CharitySite.Models.Charity

Create View

@model IEnumerable<CharitySite.Models.Charity> //To display database

@model CharitySite.Models.Charity



 @{
        ViewBag.Title = "Create";

 }

    <link href="@Url.Content("~/Content/Donate-Style.css")" rel="stylesheet" type="text/css" />

        @Html.Partial("_Form", Model);
        <div class="donatebtn">
            @Html.ActionLink("Donate", "Additionalinfo")
        </div>

        @section Scripts {
            @Scripts.Render("~/bundles/jqueryval")
        }

Model

public class Charity
{
    public int ID { get; set; }
    public string DisplayName { get; set; }
    public DateTime Date { get; set; }

    [Range(2, Int32.MaxValue, ErrorMessage = "The value must be greater than 2")]
    public Double Amount { get; set; }
    public Double TaxBonus { get; set; }
    public String Comment { get; set; }
}

public class CharityDBContext : DbContext //controls information in database 
{
    public DbSet<Charity> Donations { get; set; } //creates a donation database



}

Current Error Message

 The current request for action 'Create' on controller type 'CharitiesController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Create() on type CharitySite.Controllers.CharitiesController
System.Web.Mvc.ActionResult Create(CharitySite.Models.Charity) on type CharitySite.Controllers.CharitiesController

Any idea on how I can go about displaying validated form and database table on one page? is it possible? previously I created a form using just HTML in the "Create" view and the table displayed perfectly however adding the information to the database from a made up HTML form seems long so I used the already created form, but now the table doesnt display.

I tried

I am new to ASP.NET and am trying to validate a textbox. Basically if user inputs less than 2 or a non number how can I get the error to display. The tutorial I am trying to follow is- http://www.asp.net/mvc/overview/older-versions-1/models-data/performing-simple-validation-cs I have my code below:

Create View

   <%= Html.ValidationSummary()%>
   <%= using (HtmlBeginForm()){%>
  <div class="half-col">
                <label for="Amount">Amount:</label>
                <%= Html.TextBox("Amount")%>
                <%= Html.ValidationMessage("Amount", "*")%>
  </div>

Create Controller

 [AcceptVerbs (HttpVerbs.Post)]
    public ActionResult Create([Bind(Exclude ="ID")] Charity productToCreate)
    {
        //Validation
        if (productToCreate.Amount < 2)
            ModelState.AddModelError("Amount, Greater than 2 please");

        return View(db.Donations.OrderByDescending(x => x.ID).Take(5).ToList());  //Display 5 recent records from table 
    }

Model:

    public class Charity
{
    public int ID { get; set; }
    public string DisplayName { get; set; }
    public DateTime Date { get; set; }
    public Double Amount { get; set; }
    public Double TaxBonus { get; set; }
    public String Comment { get; set; }
}

Error

 CS1501 No overload for method 'AddModelError' takes 1 CharitySite  

I have a C# ASP.Net Razor (non MVC) webpage...

@using QuickCodeLearning.Customers.Utilities;
@{
    var cus = CustomerUtilities.GetCustomerInformation(1);
}
<html>
   <head>
      <title>
         Display a Customer
      </title>
   </head>
   <body>
    <p>@cus.fname @cus.lname @cus.FavFruit</p>
   </body>
</html>

I'm including a class library (QuickCodeLearning.Customers.Utilities) via a using statement.

Everything works fine.

enter image description here

My question is can I add this class library to my Web.Config file so that I don't have to have the using statement at the top of each page?

Here is my Web.Config file...

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="CustomersEntities" connectionString="metadata=res://*/CustomersEF.csdl|res://*/CustomersEF.ssdl|res://*/CustomersEF.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LT5V6V8W1\SQLSERVERROCKS;initial catalog=sandbox;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.web>
    <authentication mode ="Windows"/>
    <identity impersonate="true"/>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

I tried adding <page> <namespace> to the Web.Config file like this...

<?xml version="1.0"?>
<configuration>
  <pages>
    <namespaces>
      <add namespace="QuickCodeLearning.Customers.Utilities" />
    </namespaces>
  </pages>
  <connectionStrings>
    <add name="CustomersEntities" connectionString="metadata=res://*/CustomersEF.csdl|res://*/CustomersEF.ssdl|res://*/CustomersEF.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LT5V6V8W1\SQLSERVERROCKS;initial catalog=sandbox;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.web>
    <authentication mode ="Windows"/>
    <identity impersonate="true"/>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
</configuration>

But this does not work. When I remove the using statement the page stops working.

What am I missing?

I'd like to enable or disable a checkbox based on a radio button selection, however I am struggling to find the value of the clicked radio.

The radio button list looks like this

<asp:RadioButtonList ID="rbRadioButton" runat="server"></asp:RadioButtonList>

It has no items cause those are being loaded off an enum

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rbRadioButton.DataSource = Enum.GetValues(typeof(MyModel.ModelEnum));                
            rbRadioButton.DataBind();
        }
    }

I know this question is already answered but none solve my problem, I maybe having certain unknown issue. So I am again asking this question. Please help…. thanks in advance.

favorite I know this question is already answered but none solve my problem, I maybe having certain unknown issue. So I am again asking this question. Please help…. thanks in advance.

I am using Visual Studio 2015 update 3. I have developed an ASP.NET web application that uses the LocalDb provided by VS2015. I have published the website to GODADDY web server but I am not able to deploy the database. Without the database my application is working fine. I have created my MsSQL database in the GODADDY server. I am using the Build -> Publish option available in VS2015.

This is my Web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
<add name="c" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=users;Integrated Security=SSPI" />
</connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <httpModules>
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
      </httpModules>
    </system.web>    
</configuration>

How should I go about it? What should be the transformed Connection string?

I'm using a FlashHelper to show flash message to users and I need to show partial view istead of default flash message. How can I do that or is that possible or not?.

I need a helper like that:

Flash.Success("_FlashMessagePartial",model)

Or Is there any library you suggest ?

I have a web grid (from grid.mvc) it has a by default paging property which is WithPaging(int value), i want it to provide a drop down for paging (by changing drop down the integer in WithPaging(int value) should be replaced by that drop down selected value).

I tried a solution,have passed dropdown's selected value to viewbag from controller and then assigned this value to WithPaging, everything is fine but my page not refreshing...

I am developing a web site in ASP.NET forms.

If user forgets its password, he can get his new ( server generated password) on his email account. However, this works fine on localhost and on test server, but doesn't work on production windows server ( which is hosted on azure cloud).

I have tried using

user.ResetPassword

method, and also

user.ChangePassword

and nothing works.

This is my code now:

        var pw = user.ResetPassword();
        var pw2 = Membership.GeneratePassword(8,2);
        user.ChangePassword(pw, pw2);
        var em = new emailer();

        em.addParedValue("@password", pw2);

        em.isHtml = false;
        em.sendEmail("forgot.txt", user.Email, ConfigurationManager.AppSettings["defaultEmailAddress"], "Password reset!");

I get a new password on email, but cannot login with it. I also tried without

user.ChangePassword

and sending "pw" variable on email. This also did not work.

Could it be any kind of server configuration?

How to Use That Code for the ASP.net

 objBlog.myCode = "BMK" + objBlog.CreatedDate.ToString("yy") + "DES" + (objBlog.myId).ToString("00000");

This is a ASP.NET code part

txtmyCode.Text = "FDR" + output.ToString("00000");

In my web.config

<customErrors mode="On">
  <error statusCode="404" redirect="error/404.aspx"/>
  <error statusCode="500" redirect="error/500.aspx" />
</customErrors>

My 404.aspx page

<head id="Head1" runat="server">
<title>404 Error</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<link href="../css/one-page-wonder.css" rel="stylesheet" /></head>
<script type="text/javascript">
function redirect(url) {
    { alert("Please relogin") }
    window.location = "~/Index.aspx";
}

function beginSessionTimer() {
    // 3000ms = 3s
    window.setTimeout(redirect, 3000,
             "Your session has expired");
}

So my main objective here is to show the custom error page that I have done and for a moment after the page is shown. I would redirect the user back to the index.aspx page(login page). The problem is that it does pop up the message but it doesn't redirect the page.

Here is what I see on the url bar on my browser.

http://localhost:8220/terlebih/error/404.aspx?aspxerrorpath=/terlebih/nothing.aspx

And after the message is shown. I get this

http://localhost:8220/terlebih/error/404.aspx?aspxerrorpath=/terlebih/error/~/Index.aspx

I tested my code (the redirect one) It does work but not this one

I am trying to create an excel with auto fill suggestion for the cells of a specific column.

Let in my generated excel there is a column called "Name". When user write name they will get some suggestion added by me.

So, I want to add auto fill suggestion programmatically using c# and epplus.

I can't find Project template in my visual studio 2015 express edition. And I have just updated the Azure SDK to 2.8.1 but still not getting the template. I can see the azure mobile app template so is it the same one?

Screenshot of vs2015

please help me !!

Thanks, Ravi.

Im developing an ASP.net project, Im Beginner for the ASP.NET, Im write the code for but its not data save for the table, i want to save all of data with uploaded image to the SQL database. but not work correctly, please help me how can i fix it.i think its problem my uploading part, please give me a image uploading example ,thanks for the help

namespace eKnittingSimple.WebForms.InquiryOrder
{
    public partial class DesignCode : System.Web.UI.Page
    {
        #region "---- Variables & ViewStates ----"

        clsCommonMethods clsComMethods = new clsCommonMethods();

        public DataTable dtDesignCodeHelp
        {
            get { return (DataTable)ViewState["dtDesignCodeHelp"]; }
            set { ViewState["dtDesignCodeHelp"] = value; }
        }

        public String CurrentMode
        {
            get { return (String)ViewState["CurrentMode"]; }
            set { ViewState["CurrentMode"] = value; }
        }

        public int SelectedDesignCodeId
        {
            get { return (int)ViewState["SelectedDesignCodeId"]; }
            set { ViewState["SelectedDesignCodeId"] = value; }
        }

        public int SelectedUserId
        {
            get { return (int)ViewState["SelectedUserId"]; }
            set { ViewState["SelectedUserId"] = value; }
        }

        public bool ViewRight
        {
            get { return (bool)ViewState["ViewRight"]; }
            set { ViewState["ViewRight"] = value; }
        }

        public bool CreateRight
        {
            get { return (bool)ViewState["CreateRight"]; }
            set { ViewState["CreateRight"] = value; }
        }

        public bool UpdateRight
        {
            get { return (bool)ViewState["UpdateRight"]; }
            set { ViewState["UpdateRight"] = value; }
        }

        #endregion

        DesignCodeCls DesignCls = new DesignCodeCls();

        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
            if (!IsPostBack)
            {
                if ((Session["UserId"] == null))
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/WebForms/Home/Login.aspx");
                }
                else
                {
                    SelectedUserId = int.Parse(Session["UserId"].ToString());

                    string pageName = "designcode";

                    DataTable dtUp = UserPermission(pageName);
                    if (dtUp.Rows.Count > 0)
                    {
                        ViewRight = Convert.ToBoolean(dtUp.Rows[0]["isViewable"]);
                        CreateRight = Convert.ToBoolean(dtUp.Rows[0]["isCreatable"]);
                        UpdateRight = Convert.ToBoolean(dtUp.Rows[0]["isEditable"]);
                    }

                    if (ViewRight != true)
                    {
                        Response.Redirect("~/WebForms/Home/AccessDenied.aspx");
                    }
                    else
                    {
                        SetSavePermission(CreateRight);
                        SetEditPermission(UpdateRight);
                    }
                }

                ClearControls();
                EnableControls(false);
                LoadQualityReference();

            }
        }

        private void SetSavePermission(bool EnableStatus)
        {
            btnNew.Enabled = EnableStatus;
            btnSave.Enabled = EnableStatus;
        }

        private void SetEditPermission(bool EnableStatus)
        {
            btnUpdate.Enabled = EnableStatus;
            btnSave.Enabled = EnableStatus;

        }

        #endregion

        private DataTable UserPermission(string mPageCode)
        {
            int UserId = int.Parse(Session["UserId"].ToString());
            DataTable dtPermission = new DataTable();

            dtPermission = clsComMethods.GetUserWisePermissions(UserId, mPageCode);

            return dtPermission;
        }

        #region Enable Disable Controls
        private void EnableControls(bool Status)
        {
            txtDesigncode.Enabled = Status;
            txtDesignCodename.Enabled = Status;
            ddlQlty.Enabled = Status;

            if (Status == true)
            {
                txtRemarks.Disabled = false;
            }
            else
            {
                txtRemarks.Disabled = true;
            }
            chkStatus.Enabled = Status;
            btnDesignCodehelp.Enabled = Status;
        }
        #endregion

        private void LoadQualityReference()
        {
            QualityReferenceCls objQualityReference = new QualityReferenceCls();

            DataTable dtQualityReference = objQualityReference.QualityReference_SelectAll();

            ddlQlty.DataSource = dtQualityReference;
            ddlQlty.DataTextField = "Name";
            ddlQlty.DataValueField = "ID";
            ddlQlty.DataBind();

        }



        #region Button Disable
        private void DisableButtons()
        {
            btnSave.Enabled = false;
            btnUpdate.Enabled = true;
            //btnDelete.Enabled = true;
            btnInquiry.Enabled = true;
            //btnConfirm.Enabled = false;
            btnCancel.Enabled = false;
        }
        #endregion

        #region Clear Controls
        private void ClearControls()
        {
            txtDesigncode.Text = "";
            txtDesignCodename.Text = "";
            ddlQlty.SelectedIndex = 0;
            lblMsg.Text = "";
            txtRemarks.Value = "";
            chkStatus.Checked = false;
            SelectedDesignCodeId = -1;
            //lblPRTId.Text = "";


            if (CurrentMode == "Modify")
            {
                txtDesigncode.Enabled = true;
            }
        }
        #endregion

        #region New Button Click
        protected void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                ClearControls();
                CurrentMode = "Add";
                lblMode.Text = " - New Record";
                lblMode.ForeColor = System.Drawing.Color.Yellow;
                SelectedDesignCodeId = -1;
                //btnConfirm.Enabled = false;
                btnUpdate.Enabled = false;
                //btnDelete.Enabled = false;
                btnInquiry.Enabled = false;
                btnCancel.Enabled = true;
                EnableControls(true);
                txtDesigncode.Enabled = false;
                btnDesignCodehelp.Enabled = false;
                btnSave.Enabled = true;
                btnClear.Enabled = true;
                chkStatus.Checked = true;
                txtDesignCodename.Focus();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Update Button Click
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                CurrentMode = "Modify";
                lblMode.Text = " - Modify Record";
                lblMode.ForeColor = System.Drawing.Color.Yellow;
                //btnConfirm.Enabled = false;
                btnNew.Enabled = false;
                //btnDelete.Enabled = false;
                btnInquiry.Enabled = false;
                btnCancel.Enabled = true;
                txtDesigncode.Enabled = true;
                txtDesignCodename.Enabled = false;
                ddlQlty.Enabled = false;

                txtRemarks.Disabled = true;
                chkStatus.Enabled = false;
                btnDesignCodehelp.Enabled = true;
                btnSave.Enabled = false;
                btnClear.Enabled = true;
                txtDesigncode.Focus();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Inquiry Button Click
        protected void btnInquiry_Click(object sender, EventArgs e)
        {
            try
            {
                CurrentMode = "Inquiry";
                lblMode.Text = " - Inquiry Record";
                lblMode.ForeColor = System.Drawing.Color.Yellow;
                //btnConfirm.Enabled = false;
                btnNew.Enabled = false;
                btnUpdate.Enabled = false;
                //btnDelete.Enabled = false;
                txtDesigncode.Enabled = true;
                btnDesignCodehelp.Enabled = true;
                btnSave.Enabled = false;
                btnClear.Enabled = true;
                btnCancel.Enabled = true;
                txtDesigncode.Focus();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Clear Button Click
        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearControls();
        }
        #endregion

        #region Cancel Button Click
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                //lblMode.Text = "";
                CurrentMode = "Cancel";
                btnNew.Enabled = true;
                btnInquiry.Enabled = true;
                btnUpdate.Enabled = true;
                //btnDelete.Enabled = true;
                //btnConfirm.Enabled = false;
                btnCancel.Enabled = false;
                btnSave.Enabled = false;
                btnClear.Enabled = false;
                EnableControls(false);
                ClearControls();


                SetSavePermission(CreateRight);
                SetEditPermission(UpdateRight);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Save Button Click
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //if (FSaveConfirmation() == true)
                //{
                string strDesignCode;
                int statusId;

                if (CurrentMode == "Add")
                {
                    strDesignCode = "";
                }
                else
                {
                    strDesignCode = txtDesigncode.Text.ToString();
                }

                if (chkStatus.Checked == true)
                {
                    statusId = 8;
                }
                else
                {
                    statusId = 9;
                }

                int output = DesignCls.InsertDesignCode
                    (
                    SelectedDesignCodeId,
                    strDesignCode,
                    txtDesignCodename.Text,
                    int.Parse(ddlQlty.SelectedValue),
                    (string)Session["FileName"],
                    (string)Session["FilePath"],
                    txtRemarks.Value.ToString(),
                    statusId,
                    SelectedUserId,
                    CurrentMode.ToString());

                if (output > 0)
                {
                    if (CurrentMode == "Add")
                    {
                        txtDesigncode.Text = "FDR" +  output.ToString("00000");

                        lblMsg.Text = "Successfully Saved!";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                    }
                    else if (CurrentMode == "Modify")
                    {
                        lblMsg.Text = "Successfully Updated!";
                        lblMsg.ForeColor = System.Drawing.Color.Green;
                    }
                }
                else if (output == -3)
                {
                    lblMsg.Text = "Already Exists!";
                    lblMsg.ForeColor = System.Drawing.Color.Orange;
                }
                else if (output == -1)
                {
                    lblMsg.Text = "Save Unsuccessful! Code Error!";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
                else if (output == -2)
                {
                    lblMsg.Text = "Save Unsuccessful! SP Error!";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
                //}                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region DesignCode help Button Click
        protected void btnDesignCodehelp_Click(object sender, EventArgs e)
        {
            try
            {
                lblMsg.Text = "";
                txtDesignCodename.Text = "";
                txtRemarks.Value = "";
                chkStatus.Checked = false;

                DataTable dDSC = DesignCls.FGetDesignCode(txtDesigncode.Text.ToString());

                if (dDSC.Rows.Count > 0)
                {
                    dtDesignCodeHelp = dDSC;
                    Session["Help"] = "DSC";

                    gvHelp.DataSource = dDSC;
                    gvHelp.DataBind();

                    gvHelp.HeaderRow.Cells[3].Visible = false;  //Code
                    gvHelp.HeaderRow.Cells[4].Visible = false;  //StatusId 
                    gvHelp.HeaderRow.Cells[5].Visible = false;  //Remarks
                    gvHelp.HeaderRow.Cells[6].Visible = false;  //Id

                    foreach (GridViewRow gvr in gvHelp.Rows)
                    {
                        gvr.Cells[3].Visible = false;   //KnitUnitCode
                        gvr.Cells[4].Visible = false;   //StatusId 
                        gvr.Cells[5].Visible = false;   //Remarks 
                        gvr.Cells[6].Visible = false;   //GaugeId
                    }

                    mpConfirm.Show();
                }
                else
                {
                    lblMsg.Text = "No Record Found";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region Help Grid Row Command
        protected void gvHelp_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {

                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow selectedRow = gvHelp.Rows[index];

                if (Session["Help"].ToString() == "DSC")
                {
                    SelectedDesignCodeId = Convert.ToInt32(selectedRow.Cells[3].Text);

                    DataRow[] dr = dtDesignCodeHelp.Select("[DesignCodeId] = " + SelectedDesignCodeId);

                    if (CurrentMode == "Modify")
                    {
                        txtDesigncode.Enabled = false;
                        txtDesignCodename.Enabled = true;
                        chkStatus.Enabled = true;
                        txtRemarks.Disabled = false;
                        btnSave.Enabled = true;
                    }
                    else if (CurrentMode == "Inquiry")
                    {
                        txtDesigncode.Enabled = true;
                        txtDesignCodename.Enabled = false;
                        ddlQlty.Enabled = false;

                        chkStatus.Enabled = false;
                        txtRemarks.Disabled = true;
                        btnSave.Enabled = false;
                    }

                    txtDesigncode.Text = dr[0]["DesignCodeCode"].ToString();
                    txtDesignCodename.Text = dr[0]["DesignCodeName"].ToString();
                    ddlQlty.SelectedValue = (dr[0]["QualityReference"]).ToString();


                    if (Convert.ToInt32(dr[0]["StatusId"]) == 8)
                    {
                        chkStatus.Checked = true;
                    }
                    else
                    {
                        chkStatus.Checked = false;
                    }
                    txtRemarks.Value = dr[0]["Remarks"].ToString();
                }
            }
        }
        #endregion



        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.PostedFile != null)
            {
                string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

                //Save files to disk
                FileUpload1.SaveAs(Server.MapPath("~/App_Data/" + FileName));

                //Add Entry to DataBase
                String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
                SqlConnection con = new SqlConnection(strConnString);
                string strQuery = "insert into DesignCodes (FileName, FilePath) values(@FileName, @FilePath)";
                SqlCommand cmd = new SqlCommand(strQuery);
                cmd.Parameters.AddWithValue("@FileName", FileName);
                cmd.Parameters.AddWithValue("@FilePath", "~/App_Data/" + FileName);
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                try
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                }


            }
        }
    }
}

Editing: in which LOCAL folder/class/project should I create the database? I'm a newby prograiming and I have a website with 3 layers: Repository, Domain and WebInterface, now I need to create a database, in a old WindowsForm project I created the database in the Server Explorer(left menu), but when I builded the program it didn't work in others computers. Now I want to create a database inside the solution, since I have the "sql code" in the Repository I guess if should I create the database in that class, and if I would have problems with that "architeture" when I publish the website. I found lots of question similar to that but none of them was talking about it exactly

My Model has a Dataype(Datatype.Currency) whic is a decimal object.

I am trying to force the view to trigger a Numeric keypad on ipad/iphone when the user clicks into it. It works when the object is an INT but will not work for Decimal.

Heres a snippet of the model (I've tried using regular expressions to no avail):

 [Display(Name = "Bid Price")]
        [DataType(DataType.Currency)]
        //[RegularExpression("([1-9][0-9]*)")]
        public decimal BidPrice { get; set; }

Here is a snippet of the view. IS there a way to use the new { @inputtype = "number"} somehow?

<div class="col-md-10">
                @Html.EditorFor(model => model.BidPrice, new { @type= "number" })
                @Html.ValidationMessageFor(model => model.BidPrice)
            </div>

Please help if you have ever got this to work.

I have a field that is set to be a link, but needs to be displayed as either a link or a text depending on a bool hasViewDetails that is set in the code behind (c#)

here is the front-end bit for ItemTemplate:

a href ="mylinks.aspx<%# getMyLinksURL().ToString() %>&link=<%# HttpUtility.UrlEncode(DataBinder.Eval(Container.DataItem, "NewActionValue").ToString()).ToString()%>">

Is it even possible to insert an If or a Javascript code in the HTML page that would dynamically add or remove this href?