user-table
----------
name        email        start_date      end_date       status
abc        abc@abc.com   1/10/2015      1/11/2015     Expired
xyz        xyz@abc.com   5/10/2015      5/11/2015     Expired
pqr        pqr@abc.com   17/10/2015     16/11/2015    Active

I want functionality for sending mail for all end_date is today.
If time has ended the send mail before week, day before, day and day after.

For ex.

Send mail for day 16/11/2015 then also send before week, day before, day and day after, like 9/11/2015, 15/11/2015, 16/11/2015, 17/11/2015.

Note - This functionality will be automatically call WebMethod and check from database and send mails on every night 12:00 AM.

Say I have some global application setup code, defined in my Global.asax, Application_Start. For example to disable certificate checking:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // (...)
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        // (...)
    }
}

Say I also have a unit test, which depends on the code above to be run. However in my unit test, Application_Start is not called as I'm instantiating the controller directly:

var controller = new TestSubjectController();

Is there some mechanism in ASP.NET or Web API that solves this problem? What would be the best way to define the setup code, preventing duplication in my code?

Research
I've went through multiple questions on SO already. Most of them focus on unit testing Application_Start itself, however that's not the goal here. Other questions tend to look at testing using the applications external (HTTP) interface, however I'd like being able to instantiate the controller directly in my unit tests.

I'm trying to get the value from dropdownlist into my controller but I keep getting value 0.

I want to perform sorting function when a user selects the value from dropdownlist. Postback is working but when i select value from dropdownlist I just keep getting 0 not 1 or 2. Am i doing it right ? or should i define this in my controller ?

Sorry but I'm just a beginner.

Controller

    [HttpGet]
    public ActionResult Products(int page = 1, int pageSize = 9)
    {   
        Shopping db = new Shopping();
        List<Product> listProducts = db.Products.ToList();
        PagedList<Product> model = new PagedList<Product>(listProducts, page, pageSize);
        return View(model);
    }


    [HttpPost]
    public ActionResult Products(int? sortBy, int page = 1, int pageSize = 9)
    {
        sortBy = Convert.ToInt32(Request.Form["OrderBy"]);
        switch (sortBy)
        {
            case 1:
                List<Product> listProductsasc = db.Products.OrderBy(p=>p.Name).ToList();
                PagedList<Product> modelasc = new PagedList<Product>(listProductsasc, page, pageSize);
                return View(modelasc);
            case 2:
                List<Product> listProductsdesc = db.Products.OrderByDescending(p=>p.Name).ToList();
                PagedList<Product> modeldesc = new PagedList<Product>(listProductsdesc, page, pageSize);
                return View(modeldesc);
            default:
                List<Product> listProducts = db.Products.ToList();
                PagedList<Product> model = new PagedList<Product>(listProducts, page, pageSize);
                return View(model);
        }
    }

View

        <div class="col-sm-4">
            Sort by:
            @Html.DropDownList("OrderBy", new List<SelectListItem>

             {
                new SelectListItem{ Text="A-Z", Value = "1" },
                new SelectListItem{ Text="Z-A", Value = "2" }
             }, "-- Order By --" , new { onchange = "document.getElementById('Form1').submit();" })

        </div>
        <div class="col-sm-4">
            @using (Html.BeginForm("Products", "Home", FormMethod.Post, new { id = "Form1" }))
            { 
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-default" value="Filter" />
                </div>
            </div>
            }
        </div>

I have CheckBoxList I want to Check multiple items based on database value here is my code

String TargetQuery = "Select RoleID from t_Et_Role_Staff_Combination where  EmployeeID='" + EmployeeID + "'";    
SqlDataAdapter adapt = new SqlDataAdapter(TargetQuery, DBcon.con);        
DataTable dtcheck = new DataTable();
adapt.Fill(dtcheck);

protected void Page_Load(object sender, EventArgs e)
{    
    for (int i = 0; i < dtcheck.Rows.Count; i++)
    {    
        CheckBoxList1.SelectedValue = dtcheck.Rows[i][0].ToString();        
    }
}

but this checked only one item( the last item) from DataTable the previous items are not selected

[based on my database value administrator and aaa should be checked but now only aaa is selected]

enter image description here

So I have a scenario (in ASP.NET MVC) that requires that I have four tables. Three of these need to have a 1:1 relationship with the first table. When I try and run the code first migrations to define this, I get these errors:

One or more validation errors were detected during model generation:

ANA_ANASection2_Target: : Multiplicity is not valid in Role 'ANA_ANASection2_Target' in relationship 'ANA_ANASection2'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
ANA_ANASection3_Target: : Multiplicity is not valid in Role 'ANA_ANASection3_Target' in relationship 'ANA_ANASection3'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
ANA_ANASection4_Target: : Multiplicity is not valid in Role 'ANA_ANASection4_Target' in relationship 'ANA_ANASection4'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

How do I correctly activate these relationships? I don't mind losing data as we are still in development.

My schema is as follows (I'll try and simplify it):

public class ANASection2
{
    [Key]
    public int ANASection2Id { get; set; }
    [ForeignKey("ANA")]
    public int ANAId { get; set; }
    [Required]
    public virtual ANA ANA { get; set; }
}

public class ANASection3
{
    [Key]
    public int ANASection3Id { get; set; }
    [ForeignKey("ANA")]
    public int ANAId { get; set; }
    [Required]
    public virtual ANA ANA { get; set; }
}

public class ANASection4
{
    [Key]
    public int ANASection4Id { get; set; }
    [ForeignKey("ANA")]
    public int ANAId { get; set; }
    [Required]
    public virtual ANA ANA { get; set; }
}

public class ANA
{
    public int ANAId { get; set; }
    [Required]
    public ANASection2 ANASection2 { get; set; }
    [Required]
    public ANASection3 ANASection3 { get; set; }
    [Required]
    public ANASection4 ANASection4 { get; set; }
}

I am trying to run my website using The Visual Studio 2012 built in Server. I receive this error. I get this error (Note I am not using a virtual directory or an IIS Server just the Visual Studio 2012):

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

Source Error: 


Line 30:       </buildProviders>
Line 31:     </compilation>
Line 32:        <authentication mode="None">
Line 33:            <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
Line 34:       

Source File: D:\work\latest\NewPortal16-11\NewPortal8\newportal8\web.config    Line: 32 


Show Additional Configuration Errors:
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

I exported an excel file by C#, and used ClosedXML.

I exported via data table by using following code:

private void ExportGridToExcel(DataTable dt)
{
   using (XLWorkbook wb = new XLWorkbook())
   {
      wb.Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;
      wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Left;
      wb.Style.Alignment.WrapText = true;
      var ws=wb.Worksheets.Add(dt, "Talents");

      Response.Clear();
      Response.Buffer = true;
      Response.Charset = "";

      Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      Response.ContentEncoding = System.Text.Encoding.Unicode;

      string FileName = "Talent List" + DateTime.Now + ".xlsx";
      Response.AddHeader("content-disposition", "attachment;filename=" + FileName);

      using (MemoryStream MyMemoryStream = new MemoryStream())
      {           
         wb.SaveAs(MyMemoryStream);
         MyMemoryStream.WriteTo(Response.OutputStream);
         Response.Flush();
         Response.End();
      }
   }
}

But for now; I need to add not only text but also image to excel cells.

How can I add it?

I am using rdlc report and using table in it. i want to divide my report into two equal parts.when the left part is full,table must continue in the right part.like that: enter image description here

I am trying to use the Azure Runtime Reconfiguration Pattern to allow me to change a appSetting in the normal Web.config file via PowerShell (later by Microsoft Azure Web Sites Management Library). The aim is to allow some settings in an associated WebJob to be dynamically changed during runtime. Because the MVC Web.config is shared with the WebJob then changing that should be picked up by the WebJob (or at least that is my understanding).

My problem is that the RoleEnvironment.Changing event is not being called, so the web app and its webJobs are being restarted.

I have placed event set up code in the MVC Application_Start, i.e.

protected void Application_Start()
{
    RoleEnvironment.Changing += RoleEnvironment_Changing;
    RoleEnvironment.Changed += RoleEnvironment_Changed;

    //normal MVC code etc...
    AreaRegistration.RegisterAllAreas();
}

And in the Program.Main in my WebJob, i.e.

static void Main()
{
    RoleEnvironment.Changing += RoleEnvironment_Changing;
    RoleEnvironment.Changed += RoleEnvironment_Changed;

    //normal WebJob code etc...
    JobHost host = new JobHost();
    host.RunAndBlock();
}

I have added logs which prove that my RoleEnvironment_Changing and RoleEnvironment_Changed are not being called in the MVC WebApp, which means the WebApp and the WebJob are restarted. This also means the RoleEnvironment.Changing event never gets to the WebJob.

I am using Azure SDK 2.7.0

Is there a way to make a COM or Interop work on IIS Server Deployed ASP.net MVC?

I created an MVC Site which have a reference to a custom maid Interop COM to a scanner machine.

It works on Debug mode on VS but, when I try to deploy it on IIS and access it. It gives me Retrieving the COM class factory for component with CLSID {3FEDB614-C25B-448C-AED3-2D38A6C95765} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

The Thing is, the dll it self is already installed on my Machine, I think it is working on debug mode cause the IIS from VS is running differently or because I have a reference of the DLL needed.

But in IIS Deployment. Error Occurs. Any Ideas?

My main goal here is, to run the site on a Local Network and everyone can communicate with that site that has the Scanner Installed on.

Easy Idea, but hard implementation for me. And I am not even sure, if the call that I am doing is going to be made in the Host, rather than the Client.

I want to create a simple form generating engine in webforms and I am having trouble with maintaining the controls on page during postbacks.The user can select the type of the control form a DropDownList and if it is a radio button (which is in index 3), it will enable a TextBox which defines the GroupName property of the radio button.I have set a SelectedIndexChanged to handle the disabling and enabling of the txtboxGroupName.

for every control that the user adds, I want to show them a preview of what has happened so far in the form.The preview happens in a Panel control with the id of panel.

The problem is that in postbacks, the created controls disappear form the panel (which is the way it should be with asp.net postback system) and I want to preserve them.Since I don't know the control's type, I can't just put some ids in the viewstate for example to preseve the controls with those ids

I tried to do something like this but it is not working :

this is the code behind:

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

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            this.NumberOfControls = 0;
        else
            this.CreateControls();
    }

    private void CreateControls()
    {
        for (int counter = 0; counter < this.NumberOfControls; counter++)
        {
            Control temp = new Control();
            temp.ID = "control_id_" + counter.ToString();
            panel.Controls.Add(temp);
        }
    }
    protected void ddlControlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (ddlControlType.SelectedIndex)
        {
            case 0:
            case 2:
                txtboxText.Enabled = true;
                txtboxGroupName.Enabled = false;
                break;
            case 1:
                txtboxText.Enabled = false;
                txtboxGroupName.Enabled = false;
                break;
            case 3:
                txtboxText.Enabled = true;
                txtboxGroupName.Enabled = true;
                break;
        }
    }
    protected void btnAddControl_Click(object sender, EventArgs e)
    {
        Control tempControl = null;
        switch (ddlControlType.SelectedIndex)
        {
            case 0:
                tempControl = new Label();
                ((Label)tempControl).Text = txtboxText.Text;
                break;
            case 1:
                tempControl = new TextBox();
                break;
            case 2:
                tempControl = new CheckBox();
                ((CheckBox)tempControl).Text = txtboxText.Text;
                break;
            case 3:
                tempControl = new RadioButton();
                ((RadioButton)tempControl).Text = txtboxText.Text;
                ((RadioButton)tempControl).GroupName = txtboxGroupName.Text;
                break;
        }
        tempControl.ID = "control_id_" + this.NumberOfControls.ToString();
        panel.Controls.Add(tempControl);
        this.NumberOfControls++;
    }

this is my aspx page

<div class="main-wrapper">
    <form dir="rtl" id="form" runat="server">
        <label>Desired Control : </label>
        <asp:DropDownList AutoPostBack="true" ID="ddlControlType" OnSelectedIndexChanged="ddlControlType_SelectedIndexChanged" runat="server">
            <asp:ListItem Text="label"></asp:ListItem>
            <asp:ListItem Text="text box"></asp:ListItem>
            <asp:ListItem Text="check box"></asp:ListItem>
            <asp:ListItem Text="radio button"></asp:ListItem>
        </asp:DropDownList>
        <br /><br />
        <label class="label">control's text : </label>
        <asp:TextBox ID="txtboxText" runat="server" CssClass="txtbox"></asp:TextBox>
        <label class="label">group name (only for radio button)</label>
        <asp:TextBox Enabled="false" ID="txtboxGroupName" runat="server" CssClass="txtbox"></asp:TextBox>
        <br /><br />
        <asp:Button ID="btnAddControl" CssClass="btn" Text="add to form" OnClick="btnAddControl_Click" runat="server" />
        <hr />
        <h1>form preview</h1>
        <asp:Panel ID="panel" runat="server">
        </asp:Panel>
    </form>
</div>

the btnAddControl is the button that triggers the addition of a control.The control that this method creates, won't be preserved in the postbacks(whether it is another button click or changing of the dropdownlist's selected index)

the problem with this code is that nothing is being added in the panel control (I think it is because I used a generic Control type, but again, I don't know the type)

how can I preserve these controls?

UPDATE:

I recreated my code to this one but it still won't work:

    public Dictionary<string, Type> ControlTypes
    {
        get { return (Dictionary<string, Type>)Session["ControlTypes"]; }
        set { Session["ControlTypes"] = value; }
    }
    public int NumberOfControls
    {
        get { return (int)ViewState["NumOfControls"]; }
        set { ViewState["NumOfControls"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.NumberOfControls = 0;
            ControlTypes = new Dictionary<string, Type>();
        }
        else
            this.CreateControls();
    }

    private void CreateControls()
    {
        for (int counter = 0; counter < this.NumberOfControls; counter++)
        {
            string controlId = "control_id_" + counter.ToString();
            Type controlType = ControlTypes[controlId];
            panel.Controls.Add(LoadControl(controlType, null));
        }
    }

    protected void ddlControlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (ddlControlType.SelectedIndex)
        {
            case 0:
            case 2:
                txtboxText.Enabled = true;
                txtboxGroupName.Enabled = false;
                break;
            case 1:
                txtboxText.Enabled = false;
                txtboxGroupName.Enabled = false;
                break;
            case 3:
                txtboxText.Enabled = true;
                txtboxGroupName.Enabled = true;
                break;
        }
    }

    protected void btnAddControl_Click(object sender, EventArgs e)
    {
        Control tempControl = null;
        switch (ddlControlType.SelectedIndex)
        {
            case 0:
                tempControl = new Label();
                ((Label)tempControl).Text = txtboxText.Text;
                break;
            case 1:
                tempControl = new TextBox();
                break;
            case 2:
                tempControl = new CheckBox();
                ((CheckBox)tempControl).Text = txtboxText.Text;
                break;
            case 3:
                tempControl = new RadioButton();
                ((RadioButton)tempControl).Text = txtboxText.Text;
                ((RadioButton)tempControl).GroupName = txtboxGroupName.Text;
                break;
        }
        string controlId = "control_id_" + this.NumberOfControls.ToString();
        tempControl.ID = controlId;
        panel.Controls.Add(tempControl);
        this.NumberOfControls++;
        ControlTypes.Add(controlId, tempControl.GetType());
    }

what I did was to create a dictionary with control's id and type and store it in the session and then reload the type of the control in page load and render it on page using LoadControl method.But I want to know why this code won't work?

We've recently switched from HyperV to VMWare, moving all of our servers to a new datacenter. Everything was running fine before we moved our servers, but now we have an interesting issue. Only new thing is a change of IP addresses and new virtual LAN interfaces on the machines. Scenario: We've got an MSSQL server hosting multiple databases. We've got one machine hosting multiple websites. Both machines are virtualized. Only one of the websites hosted on the IIS can so far connect and communicate with the SQL Server, while all other sites return the error: "The specified network name is no longer available". It's "random" which of the websites actually gets to connect ie. it's the first website to wake up that gets the connection. If we restart the IIS machine, we can force one of the other websites to work, but not all of them.

I hope you gus have any ideas on how to solve this issue. It's a standard IPV4 network.

Best regards, Martin

I am trying to find the lowest value between the length and width. I then need to check if that value is between 0.01 and 0.80 but I am getting some errors on the part `<= 0.80M``in the if statement.

decimal min = Math.Min(Length, Width);

if(min >= 0.01M || <= 0.80M)
{

}

Error 147 Invalid expression term '<='

Error 148 ) expected

Thank you everyone for the help. I know it was a simple question but I would appreciate if people stopped down voting this. I wasn't sure about something and I asked for help. I'm sure this question will be usual to someone else to

I need to pass a value to a textbox but this textbox can't be writable directly by the user. I'm calculating the value using jason:

<script type="text/javascript">
    $(document).ready(function () {
        $("#txtid").change(function () {
            $.ajax({
                url: '/CommissionsFinals/GetTarifa',
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: { clientID: $("#DDLCliente").val(), consultorID: $("#DDLConsultor").val() },

                success: function (tarifa) {
                    //response(tarifa.
                    $('#txtid').val(tarifa).autocomplete

                },
                error: function () {
                    alert('Error!');
                }
            });

        })
    });

The textbox changes his value when i try to input a diferente value. The value is being calculated by the 2 parameters (clientId,consultorId) which are selected in 2 diferente DropDownLists. How do I get the value automatically after selecting those 2 values from the DropDownList?

<th>
    @Html.DropDownListFor(m =>m.ManagerId, new SelectList(ViewBag.Manager, "ManagerId", "NomeCompleto"), "Seleccione o Manager", new { @class = "form-control", @id = "DDLManager" })
</th>
<th>
    @Html.Label("Consultor", htmlAttributes: new { @class = "control-label col-md-2" })
</th>
<th>
    @Html.DropDownListFor(m => m.ConsultorId, new SelectList(ViewBag.Consultor, "ConsultorId", "NomeCompleto"), "Seleccione o Consultor", new { @class = "form-control", @id = "DDLConsultor" })
</th>

I am pretty advanced in C# but a newcomer in the world of ASP.NET.

My HomeController.cs:

public ActionResult Index()
{
    // tuple -> item1 = key string / item2 = assigned list
    var configList = new List<Tuple<string, List<string>>>();
    configList = fillItWithSomeData(..)
    ViewBag.ConfigSettings = configList;

    return View();
}

My Index.cshtml:

<div>
    <div class="row">
        @foreach (var elements in ViewBag.configSettings)
        {
            <div class="col-md-8 checkbox">
                /*I NEED A BUTTON HERE*/
                <label>
                    <input type="checkbox">@elements.Item1
                </label>
            </div>
            foreach (var listElement in elements.Item2)
            {
                <div class="col-md-8 col-md-offset-1 checkbox">
                    <label>
                        <input type="checkbox">@listElement
                    </label>
                </div>
            }
        }
    </div>
</div>

Every key string in my list contains a list of strings. (look at var configList) In my view I want to have a button for each key string which should be able to open or close the assigned list of the respective key string. I currently use ASP.NET-MVC. How can I program that? In C# or do I need to use JS for that? I really have no idea. Thanks in advance.

We're running a web application on IIS 8.5, against ASP.NET 2 in Classic mode. We trying to make use of a handler but it seems to be having no effect:

<system.webServer>
  ...
  <handlers>
    <add name="HTMHandlerMapping" path="*.htm" verb="*" type="{namespace}.{class}, {assembly-name}" resourceType="Unspecified" requireAccess="Script" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" resourceType="Unspecified" preCondition="classicMode,runtimeVersionv2.0,bitness32" />
    ...
  </handlers>
  ...
</system.webServer>

The answer here seems to suggest that this is not possible for classic mode with URL a rewriting module?

I've coded a few sites in C# - all self taught. I have to admit, I've made lots of mistakes in the past, with regard to design choices, however, I'm getting to the point where I now understand more about C# and Asp.Net - enough to start asking the right questions.

I recently looked back at the code on one of my first sites. One approach I took was to add a guard clause to absolutely everything - all incoming parameters on every constructor and method throughtout.

I'm now starting a new site and want to ensure I do the 'right amount' - this is something that only becomes apparent with more experience.

I also want to start logging things using NLog. Although there's unlikely to be a right or wrong answer I'd appreciate some advice as to what questions I should be asking myself and how far I should go with the guard clauses - should I throw, log and throw, or let it fall ungracefully on its backside?

I need to generate following HTML dynamically (a BulletedList, two Panels and a HyperLink) using asp.net C# Web.UI.WebControls

 <ul>
    <li>
        <div class="xxx"><a href="xxx">Home</a></div>
        <div class="xxx">
            <div style="width:500px; height:200px;">
              THis is a test
            </div>
        </div>
    </li>
 </ul>

I try to use BulletedList but I can't insert Panels and a HyperList into ItemList. The requirement is to use asp.net Web Controls (Not HTML directly) and generate above HTML dynamically with UI Web Controls.

Dose anyone know how to do it with ASP.net UI.WebControls?

I want to implement navigation menu in ASP.Net MVC4 in Razor view. It will show user how he/she has traversed the pages and will be able to go back to any previous pages in hierarchy.

Eg. If user is browsing products, and if he has reached 'Mobile phones' browsing, I would like navigation menu to display something like below:

Home » All Products » Mobiles & Tablets » Mobile phones

Please note in above navigation, 'Mobile phones' will be only label, whereas other navigation items will be link. User can click on this link and go back to any previous page.

Please suggest approach to implement this.

Asp.net MVC EF with Identity component.

I need to retrieve all files from a directory and add them to the database when the application starts. Eg I can not put it in the HomeController because then it will be every time someone visits the page.

This is the code I want to run.

DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Images"));
            var folders = di.GetDirectories().ToList().Select(d => d.Name);

  var files = di.GetFiles();
            foreach (var file in files)
            {
                var image = new Image{ name = file.ToString() };
                db.Images.Add(image);
}

I have tried to put it here

    public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
            {
    //Here
                protected override void Seed(ApplicationDbContext context)
                {
    //Here
    }
}

But get error that I cant user Server.MapPath

Where should I put my code?

I have a gridview which is accessed from another page. First page sends an Id as a request parameter to a SP so the grid gets populated.

But other pages than the first page of grid comes blank because the aforementioned Id is not sent with page changes.

We use a custom pagination without any PageIndex change function but I have some "addparameter" and other request manipulation functions.

I'm trying to send the Id to other pages too but I can't get it persist on postbacks. I tried to set a viewstate variable with the first coming request parameter of Id and make it persist through postbacks. I used a session variable before but I was told not to use it again and to do it request parameters. When I try the viewstate variable, first time it comes right but then it becomes 0 on other pages too because the request parameter gets sent as null to other pages (checked when I assigned the viewstate parameter assignation) and each pageload sets the viewstate to 0.

What is the correct way of doing this? How can I keep the first coming request parameter and send it as a request parameter again with each new page?

Assigning the request parameter to viewstate (apparently wrong approach)

public int FirmaId
    {
        get
        {
            if (ViewState["FirmaId"] == null)
                ViewState["FirmaId"] = Convert.ToInt32(Request["FirmaId"]);
            return (int)ViewState["FirmaId"]; 
        }
        set { ViewState["FirmaId"] = value; }
    }

page load and grid binds (only relevant parts)

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Convert.ToInt32(Request["Page"]) > 1)
            {
                //int FirmaId = Convert.ToInt32(Request["FirmaId"]);
                pcBottom.AddCustomParameter("FirmaId=" + FirmaId);
            }


            if (!string.IsNullOrEmpty(Request["FirmaId"]))
            {

                trFirmaAdi.Visible = false;
                BindFirmaAracList(false);
                fldImport.Visible = true;
                fdlFirmaSecim.Visible = true;
                tdIslemFirma.Visible = true;

                DataRow dr = FirmaDB.Firma_Get(Convert.ToInt32(Request["FirmaId"])).Tables[0].Rows[0];
                string adi = dr["adi"].ToString();
                string vergino = dr["vergiNo"].ToString();
                lblIslemFirmaAdi.Text = adi;
                lblIslemFirmaVergiNo.Text = vergino;

                //OnayFirmaId = Convert.ToInt32(Request["FirmaId"]);
                //fsFirma_Select(fsFirma, null);
            }



            DataRow db = AdminDB.FirmaArac_Get_Count().Tables[0].Rows[0];
            string cekici = db["Adet"].ToString();
            DataRow dt = AdminDB.FirmaArac_Get_Count().Tables[0].Rows[1];
            string dorse = dt["Adet"].ToString();
            lblCount.Text = "Toplam çekici:" + cekici + "-" + "Toplam dorse" + dorse;

        }
    }

    #region Parameters
    private int _pageRowCount = 500;
    //private int _currentPageIndex = 1;
    public int CurrentPageIndex
    {
        get { return pcBottom.CurrentPageId; }
        set { pcBottom.CurrentPageId = value; }
    }


    #endregion Parameters


    private void BindFirmaAracList(bool KeepLabel)
    {
        int FirmaId = 0;
        if (!string.IsNullOrEmpty((string)Request["FirmaId"]))
            FirmaId = Convert.ToInt32(Request["FirmaId"]);

        string firmaadi = (txtSearchFirmaAdi.Text == string.Empty ? null : txtSearchFirmaAdi.Text);
        string plakano = (txtSearchPlakaNo.Text == string.Empty ? null : txtSearchPlakaNo.Text);

        int TotalCount;
        int Start = (CurrentPageIndex - 1) * _pageRowCount;

        //Request["Start"] = Start;

        DataSet ds = AdminDB.FirmaArac_List(
            FirmaId, firmaadi, Convert.ToInt32(cmbSearchAracTipi.SelectedValue), plakano, Convert.ToInt32(drpApproved.SelectedValue)
            , Start, _pageRowCount, out TotalCount);
        gvFirmaAracList.DataSource = ds;
        gvFirmaAracList.DataBind();

        int intTotalCount;
        int intCurrentCount;


        intTotalCount = TotalCount == -1 ? 0 : TotalCount;
        intCurrentCount = ds.Tables[0].Rows.Count - 1;

        pcBottom.TotalRowCount = intTotalCount;
        pcBottom.PageRowCount = _pageRowCount;
        pcBottom.CurrentRowCount = intCurrentCount;

        int p = Convert.ToInt32(Request["Page"]);
        //if (Convert.ToInt32(Request["Page"]) > 0)
        //{
        //    pcBottom.AddCustomParameter("FirmaId=" + FirmaId);
        //}


        pcBottom.BindPaging();

        pcBottom.Visible = intTotalCount > 0;
}