ASP.NET

123K

Solutions

28K

Contributors

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

Share tech news, updates, or what's on your mind.

Sign up to Post

Perhaps I am over-thinking this but what I need to do is see what the time difference it is from the start session time (1 minute) subtracting the current time.
<script type="text/javascript">
var mySessionTimer;

@functions {        
    public int PopupShowDelay
    {
        get {
            DateTime currentSetTimeout = DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout);
            DateTime currentServerTime = DateTime.Now;
            TimeSpan duration = (currentServerTime.Subtract(currentSetTimeout));

            return 60000 * (int)duration.TotalMinutes;
        }
    }
}

function callJSSessionTimer() {
    var sessionTimeoutWarning = @PopupShowDelay;
    var sTimeout = parseInt(sessionTimeoutWarning);

    mySessionTimer = setTimeout('SessionEnd()', sTimeout);
}

function SessionEnd() {
    clearTimeout(mySessionTimer);
    window.location = "/Account/sessionover";
}

@if (userInfo != null)
{
    if (userInfo.chosenAMT == "True")
    {
        @:callJSSessionTimer();
    } else
    {
        @:clearTimeout(mySessionTimer);
    }
} else {
    @:clearTimeout(mySessionTimer);
}
</script>

Open in new window

So for the value for duration is -00:01:00 which technically is correct since currentSetTimeout is 1 minute and it gets todays date/time which is a minute away since its subtracting it fromcurrentSetTimeout.

So the point of all of this is to keep track of the remaining session time when the user jumps from page to page. Currently when the user goes to another page, it resets the time and its not accurate.

How can I go about doing this the way I need it?
0
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Hello all. I have an ASP.NET web forms application that has been working fine until a recent change from cookies to session variables (don't think that has anything to do with it but ...) and an upgrade of the Telerik controls.
The same code behind, in two separate ASPX pages (print and reprint), behave differently. They both use this format:

1 Dim PrintCmd as String = "PrintForm.aspx?var1=value&var2=value..."
2 PrintCmd =  "<script language=javascript> {window.open('" & PrintCmd & "', '_blank');}</script>"
3 WriteNlog.Info(PrintCmd)
4 Response.Write(PrintCmd)
5 Response.Write(PrintCmd.Replace("Some Text","Other Text")
6 CallNlog.Info("Returned from print")

The page being called is a simple ASPX that copies the query values to labels and then the body performs window.print() then window.close(). It makes an NLog entry at preload and load, when it works.

Page1.aspx executes 1,2,3 and 6. Logging in the PrintForm.aspx does not occur, no error is reported, as if 4 and 5 are comments.
Page2.aspx executes 1 through 6 without fail.

Both origination forms use the same site master with Telerik controls (RadScriptManager, RadMenu, RadAjaxLoadingPanel and RadAjaxManager).
The print page is pure ASP webform.

Alternately I have tried:
4 ClientScript.RegisterStartupScript(Me.GetType(), "receipt1", PrintCmd, True)
5 ClientScript.RegisterStartupScript(Me.GetType(), "receipt2", PrintCmd.Replace("Some Text","Other Text"), True)

Again, page2 works flawlessly and …
0
I have a modalPopupExtender control with a Panel and inside the Panel I have an iFrame thats source is another form. This is the way my boss wanted it done. So in the other form where I have 3 different html tables. So whenever this form gets called up it will know which table  should be visible and which should not. This is all fine. My only problem is resizing my panel and iFrame. When the modalPopupExtender gets called the iFrame is either too big and the Panel too small or vice cersa. Now, in my calling form I have a procedure that checks the browser and sets the height accordingly(the width of the iFrame is set to 95% and that, for some reason, works?? But the height is my nemesis and, like I said, depending on which html table will show is dependent on the height that should be set.
This CANT be so hard that I have to deal with major gaps in my form/popup. It looks horrble. I have attached a pictures of the 3 different heights I need and Im hoping that someone can let me know what Im doing wrong and an easy way to go about fixing it...

FYI, the 3 pics I have attached are in IE and they are worse in the other browsers.
I can deal with 1 and 3 but the 2nd pic attached is unacceptable....

Thanks in advance....And anything needed from me please ask and I will send it right over

PLEASE HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Problem 1Problem 2Problem 3
0
On my new MBAM Server , IIS Keep crashing.

I have  the following message when I go on the MBAM Admin site.
Server Error in '/HelpDesk' Application.
Runtime Error
Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.  

I look for a solution on Google.. did find anything.

This is the detail on the server event log  (Some information has been tagged as HIDDEN)
ASP.NET 4.0.30319.0 Event ID 1309.  
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 8/16/2017 11:34:09 AM
Event time (UTC): 8/16/2017 3:34:09 PM
Event ID: 04f1f8a5a6214bc3a2df384ae28e4ea1
Event sequence: 2
Event occurrence: 1
Event detail code: 0
 
Application information:
    Application domain: /LM/W3SVC/2/ROOT/HelpDesk-11-131473712497274086
    Trust level: Full
    Application Virtual Path: /HelpDesk
    Application Path: C:\inetpub\Microsoft BitLocker Management Solution\Help Desk Website\
    Machine name: Hidden
 
Process information:
    Process ID: 3244
    Process name: w3wp.exe
    Account name: Hidden
Exception information:
    Exception type: HttpException
    Exception message: Instance failure.
   at System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app)
   at …
0
I have a form with Submit.
I need to append a hashtag (#) so I can open the page and goto an anchor called '#searchresults'.
Here is my code;

	
var searchTerm = Request.QueryString("qa_searchForm")
Out ('<form action="" method="get" style="vertical-align:middle; margin:20px 0px 0px 0px; background:url(images/Community/graphic_com_search_field.jpg) no-repeat">');
Out ('<input type="text" value="Enter search terms here to search ALL categories..." name="qa_searchForm" style="width:360px; font-size:1em; margin-left:60px; height:39px; line-height:39px; background-color:#EAE8D4; border:0; vertical-align:middle; color:gray;" onblur="if(this.value==&#39;&#39;) { this.value=&#39;Enter search terms here to search ALL categories...&#39; }" onfocus="if(this.value==&#39;Enter search terms here to search ALL categories...&#39;) { this.value=&#39;&#39; }"/>');
Out ('<input type="hidden" value="'+nPage+'" name="page"/>');

Open in new window


I am using a hidden value to insert the page number (variable nPage).
If I enter "test", the resulting querystring is:

/default.aspx?qa_searchForm=test&page=Retailer-QA

So far, so good.

If I try to add another hidden value:
Out ('<input type="hidden" value="#searchresults" name="anchor"/>');

Open in new window


I get the following result:
/default.aspx?qa_searchForm=test&page=Retailer-QA&anchor=%23searchresults&x=90&y=17

What do I do to get the following needed querystring that has the anchor '#searchresults':

/default.aspx?qa_searchForm=test&page=Retailer-QA&anchor=#searchresults

Thanks!
Russ :)
0
I see alert message "Process cannot access the file because it is being used by another process".
when I click the button at third time. It seems reading is okay. but when i click the button to write something inside  to the xml.
it fails. how can i resolve this issue?

I know the  "Process cannot access the file because it is being used by another process". continue to happen the new message is sent.
sendMsg_Click(), but that does not mean the issues came from there.

And I check all controllers I used, and when the file is opened, it is closed immediately.

  protected void Page_Load(object sender, EventArgs e)
        {
            phoneNoList.DataSource = Utility.Controller.GetUniquePhoneNo(fromPhoneNo);
            phoneNoList.DataBind();
}

  protected void sendMsg_Click(object sender, EventArgs e)
        {
		 #region add a record to all message xml
                Domain.User u = new Domain.User();
                u.fullName = fullName.Text;
                u.from = "+1" + fromPhoneNo;
                u.to = "+1" + toPhoneNo.Text;
                u.body = body.Text;
                u.dateTimeSent = DateTime.Now.ToString();
                u.direction = "outbound-reply";
                string result = Utility.XML.Add(Utility.Controller.filePathUserMessagesAll, u);
                #endregion


}

  public static string Add(string inputFilePath,Domain.User u)
        {
            XDocument doc = XDocument.Load(inputFilePath);
            XElement user = 

Open in new window

0
Below codes is to return .net datatable, and I use asp.net repeater to bind it. everything is working except the list does not sort by date and time. The data source starts from query3.

Not sure why. and hope some experts can help out.

Thanks

var query3 = query1.Concat(query2).OrderBy(z => z.DateTimeSent);

           


             
public static DataTable GetConversation(string sid, string token,string accountPhoneNo, string twilioPhoneNo)
        {  
            string clientPhoneNo = string.Empty;
            string inputFilePath = filePathUserMessagesAll;
            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.AddRange(new DataColumn[]
           {
                new DataColumn("Body",typeof(string)),
                new DataColumn("DateCreated",typeof(string)),
                new DataColumn("Direction",typeof(string)),
                new DataColumn("SelectedPhoneNo",typeof(string))
           });
            XDocument xdoc = null;
            using (XmlReader xr = XmlReader.Create(inputFilePath))
            {
                xdoc = XDocument.Load(xr);
                var query1 = from t in xdoc.Descendants("User")
                             where 
                             (
                             t.Element("From").Value.ToLower() == "+1" + accountPhoneNo.ToLower()
                             ) //client phone
                             select new
                             {
                   

Open in new window

0
I am trying to convert an @Html.Textbox image button to a submit button with  the onclick calling a Javascript function.

Here's what I have:
@Html.TextBox("Next", null, new {type = "image", src = @Url.Content("../App_Themes/icons/button_next.png"), @class = "imgbottom", onclick = "javascript: ValidateSelection ($(\"[name$='selectedItems']:checked\"))"})

Here's what I've tried:
<input type="button" value="Next" onclick="ValidateSelection (selectedItems.checked)">

and my Javascript function:
function ValidateSelection(item) {
    if (item == null || item.length == 0) {

        var validationSummary = $('.validation-summary-errors ul');
        if (validationSummary.length > 0 && $('.validation-summary-errors ul li').length == 0) {
            validationSummary.append('<li>' + "Please select at least one item" + '</li>');
        }
        var errors = $("[name='ErrorMessage']");
        if (errors.length > 0) {
            errors.hide();
        }
        var buttonGenerateReport = $("#GenerateReport");
        if (buttonGenerateReport.length > 0) {
            buttonGenerateReport.hide();
        }
        event.preventDefault();
    }
}
0
I had this question after viewing Required field validator not working.

                    <div class="modal-body">
                        <p>Some text in the modal.</p>
                      <asp:TextBox ID="txtStandType" runat="server" name="StandType"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" Visible="false" ControlToValidate="txtStandType"></asp:RequiredFieldValidator>
                        <br />
                        <asp:CheckBoxList ID="chkFormNamesAdd" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">
                        </asp:CheckBoxList>
                     
                    </div>
                    <div class="modal-footer">
                        <asp:Button ID="btnAddStandTypeModal" runat="server" Text="Save" Style="float: left" OnClick="btnAddStandTypeModal_Click" />
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                    </div>

Open in new window


protected void btnAddStandTypeModal_Click(object sender, EventArgs e)
    {
        //try
        //{

        string txt = txtStandType.Text;

        if (txt == "")
        {
            RequiredFieldValidator1.Visible = true;
        }

        else
        {
                con.Open();
            

Open in new window

0
I have xml codes below and want to achieve two goals

1. Load XML into MS SQL Table.
2. I want to use the <Element> name as field name so I do not have to create new ms table in advance.

so the table structure will look like below
GetCarriersPlansBenefitsResponse
ExtensionData
RequestId
Plans
Plan
PlanId
State
and etc.

and the xml has around 50+ k records.

<?xml version="1.0" encoding="utf-8"?>
<GetCarriersPlansBenefitsResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExtensionData/>
<RequestId>208793868asdfasdf</RequestId>
<PodId>ws_V2_A2_S2asdfasd</PodId>
<TotalMilliseconds>5145sdfads</TotalMilliseconds>
<LoadSequenceId>5392823432</LoadSequenceId>
<Carriers>
	<Carrier>
		<Version>1.0</Version>
	</Carrier>
	<Plans>
		<Plan>
			<PlanId>123</PlanId>
			<State>CA</State>
		</Plan>
	</Plans>
</Carrier>

Open in new window

0
Free Tool: SSL Checker
LVL 9
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I need to display HTML report from and XML response in ASP.NET application.
Say, I have a default.aspx page and in the default.aspx.cs page, I use a web client to make a request and get a response.
once i get a response (sample below), how should I read/display the embedded Html report from my XML response file in default.aspx page.

<Response>
    <htmlreport><![CDATA[<html>
        <head/>
        <body/>
        </html>
     ]]>
    </html>
</Response>
0
Hi,

In my site, the user logs in and if the role is admin they are directed to the Admin Console.  When this user logs out Session values are killed. But after log out, if they simply paste the adminconsole.aspx URL into the browser, they are allowed access.  This appears to be because the admin page is cached and the cached page is served.

I like the cache on the admin console page as it is simply a static page.

Is there a way around this issue while still using the page cache? Or is the only solution to NOT cache the page?

Thank you

Vince
0
I came across this site and it has the answer to the questions. I want to know why the answers are that.

   public class A
        {
            public A()
            {
                var p = "In A";
            }

            static A()
            {
                var p = "in Static A";
            }

            public void Method()
            {
                var p = "In Method A";
            }

        }



        public class B:A
        {
            public B()
            {
                var p = "In B";
            }

            static B()
            {
                var p = "in Static B";
            }

            public void Method()
            {
                var p = "In Method B";
            }

        }

Open in new window


1. A a = new A();  -- Why does it call the "In static A" first and then "In A"?  Static methods can't be called with "new"

2. B b = new A();  -- why is this an error? B inherits from A

3. A c = new B();  -- this calls "in static B" first, then "in Static A", then "In A" and then "In B".  Same as #1. Why is it calling "static" method first?  It inherits from A ...that's why it calls "in Static A", then "In A" next, correct?
0
I do not see any options to add Microsoft Reporting to Visual Studio 2013.  I need to add this and the report viewer control.  Thank you
0
I have a legacy app that I am converting to ASP.NET. The current application uses Oracle logins and roles for authentication and authorization. The dedicated DBA thinks using a single service account (stored encrypted in the web.config) with read / write / edit / delete table access is a bigger security risk than hundreds of users with direct database logins / access. The Oracle logins / roles are used to control access to sections on the UI AND the related database objects (i.e. access rules are generally duplicated on the front end and the back-end). I'm looking for ideas / sources to support the service account method for database access, as far as security risks go. Thanks in advance!
0
I have:
action="https://test.secure.touchnet.net:8443/****.jsp" method="post" target="_self" id="hidden_calc"
<input type="hidden" name="UPAY_SITE_ID" value="*">
<input type="hidden" name="EXT_TRANS_ID" value="whatever">

I need to add
<input type = "hidden" name = "BILL_NAME" value = "aName">
<input type = "hidden" email = "email" value = "aName@gmail.com">

I need to have this all run in the code behind.

any help will be appreciated
0
Please be kind, I am a newbie to this and have done the web research and everything points back to the example files attached.  My ultimate goal is to have a web page where the user clicks on a button and a PS script runs returning a formatted web page.  Trying to crawl before walking

The issue I am having is when I run the code I am getting a Server Application Error "Parser Error Message: 'PowerShellExecution.Default' is not allowed here because it does not extend class 'System.Web.UI.Page'", but can't find any details on how to correct the issue.

Thanks,
Default.aspx.cs
WebForm1.aspx
0
Hi, I need to implement a Google Maps Geofence with MVC 5.

Anyone has a sample?
0
Hi,

The code I have below has been working fine without parameters. I added a new parameter into sp, (the sp is working), but I am getting

Newline in constant

from ASP.net, any ideas?  thanks
    private void load1(SqlConnection sqlConnection)
    {

        SqlCommand connLoad = new SqlCommand("st_test", sqlConnection);
        connLoad.CommandType = CommandType.StoredProcedure;           
        connLoad.Parameters.Add("@Category, System.Data.SqlDbType.VarChar, 20).Value = "test";//Request.QueryString["category"];

        SqlDataAdapter da = new SqlDataAdapter(connLoad);

        using (DataTable dt = new DataTable())
        {

            da.Fill(dt);
            using (XLWorkbook wb = new XLWorkbook())
            {
                
                var ws = wb.Worksheets.Add(dt, "123");
                ws.Row(1).Style
                        .Fill.SetBackgroundColor(XLColor.YaleBlue)
                        .Font.SetBold();

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=myexcel.xlsx");
                //Response.TransmitFile(FilePath); 

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {

                    wb.SaveAs(MyMemoryStream);
                    

Open in new window

0
Free Tool: Site Down Detector
LVL 9
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I've been using an iframe to embed content from a 3rd party vendor for over a year now but recently, particularly in Chrome, the content on the page is flashing and not fully loading, ever, so it seems. I haven't changed my code (see below) so I'm not sure what the problem is. I'm researching solutions but they all seem very complicated at that point, if they would even work. Some involve php and I'm not familiar with that AT ALL so I don't know if that is even an viable option. Please help?

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SFATouchTasks.aspx.cs" Inherits="SFATouchTasks" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .page
        {
            width: 1150px;
            height: 100%;
        }        
        .header
        {
            background: #FFF;
            width: 100%;
        }        
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div id="divEmbed" style="height: 300px;">
        <iframe id="ifm" name="ifm" width="100%" height="300%" frameborder="0" src="http://x.x.xxx.xxx:xxxx/app/main#/dashboards/589e1fed677202f430000031?embed=true"
            scrolling="auto" style="float: left;"></iframe>
    </div>
</asp:Content>

Open in new window

0
I have an MVC application. I am new to MVC. I have a HomeController with a function, getUserId,  that returns the UserId of the current user. I want to display the result of that function in my index.cshtml page. Something like "Your are logged in as: smtihs". How do I call the result of the function from the cshtml page? Thanks for any help.
0
I am trying to add required field validator to a textbox which is in modal popup the checkbox below the textbox disppear, I tried to put validation though javascript also but it is not working please help

Let me show u the screenshot what i am trying to say

RequiredModal.png
Below is my modal popup in which the textbox is present

but when i am trying to add the validator,  the modal popup loads on a page along with the validator. it show below screenshot

AfterRequiredAdd.png

I have tried the validation using javascript code also but not working

Here is my code:-

<div class="modal-body">
                        <p>Some text in the modal.</p>
                      <asp:TextBox ID="txtStandType" runat="server" name="StandType"></asp:TextBox>
                        <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtStandType"></asp:RequiredFieldValidator>--%>
                        <br />
                        <asp:CheckBoxList ID="chkFormNamesAdd" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">
                        </asp:CheckBoxList>
                     
                    </div>
                    <div class="modal-footer">
                        <asp:Button ID="btnAddStandTypeModal" runat="server" Text="Save" Style="float: left" OnClick="btnAddStandTypeModal_Click" />
                        <button type="button" class="btn 

Open in new window

0
Hi HainKurt,

Perhaps, you can help me one more time on this?

I am trying to remove a dynamically generated row in Repeater.

The code below is generating an error:

protected void btnDelete_Click(object sender, EventArgs e)
{
    int rowIndex = 0;
    int rowID = e.RowIndex;
    lblTotal.Text = "0";
    if (ViewState["CurrTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrTable"];
        if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= Repeater1.Items.Count; i++)
            {
                TextBox tbboatregNum = (TextBox)Repeater1.Items[rowIndex].FindControl("txtboatregNum");
                TextBox tbPayerret = (TextBox)Repeater1.Items[rowIndex].FindControl("txtPayerret");
                TextBox tbCGvesselNum = (TextBox)Repeater1.Items[rowIndex].FindControl("cgaurdNumber");
                TextBox tbCGtaxpayerret = (TextBox)Repeater1.Items[rowIndex].FindControl("cguardreturnedval");
                dtCurrentTable.Rows[i - 1]["boatregNum"] = tbboatregNum.Text;
                dtCurrentTable.Rows[i - 1]["taxpayerret"] = tbPayerret.Text;
                dtCurrentTable.Rows[i - 1]["CGvesselNum"] = tbCGvesselNum.Text;
                dtCurrentTable.Rows[i - 1]["CGtaxpayerret"] = tbCGtaxpayerret.Text;
                rowIndex++;
            }

            if (e.RowIndex < dtCurrentTable.Rows.Count)
            {
                dtCurrentTable.Rows.Remove(dtCurrentTable.Rows[rowID]);
            }
  

Open in new window

0
I am learning ASP.NET Core using somebooks and tutorial, but nearly all of them use a localdb for the database. I would like to create the database into the local Instance of SQLServer Installed on my machine and need help with the syntax for providing the connection string for this purpse.
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
             // This is the connection string I am using currently for mssqllocaldb
             optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = BookPost; Trusted_Connection = True; ");
         );
            //  This is the connection string that use I a WPF application to connect to SQLServer intance on my machine
    //< add name = "LibraryEntities" connectionString = "metadata=res://*/Fish.csdl|res://*/Fish.ssdl|res://*/Fish.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=FAHEEMPC\SQLEXPRESS;initial catalog=Library security info=True;user id=sa;password=abcepassword;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName = "System.Data.EntityClient" />

}

Open in new window


Thank you for your help.
0
Hopefully, this is simple.

I have the following GridView loop:

        foreach (GridViewRow row in Gridview1.Rows)
        {
            string registerNumber = (row.FindControl("txtNum") as TextBox).Text;
            if (row.RowIndex == 0)
            {
                this.SetInitialRow2(registerNumber);
            }

            else
            {
                AddNewRow2(registerNumber);
            }
            foreach (RepeaterItem Item in Repeater2.Items)
             {
                  (Item.FindControl("BtnAdd2") as Button).Visible = Repeater2.Items.Count > 1;
                  (Item.FindControl("btnDelete") as Button).Visible = Repeater2.Items.Count > 1;
             }
            }

Open in new window


This works good.

However, I am trying to use same logic but in Repeater but I am stuck on this this line:

        if (Items == 0
...

Open in new window


How do I write this line in Rpeater?

     if (row.RowIndex == 0)

Open in new window


Here is the entire code:

        foreach (RepeaterItem Items in Repeater1.Items)
        {
            string registerNumber = (Items.FindControl("txtNum") as TextBox).Text;
            if (Items == 0)
            {
                this.SetInitialRow2(registerNumber);
            }

            else
            {
                AddNewRow2(registerNumber);
            }
            foreach (RepeaterItem Item in Repeater2.Items)
             {
                  (Item.FindControl("BtnAdd2") as Button).Visible = Repeater2.Items.Count > 1;
                  (Item.FindControl("btnDelete") as Button).Visible = Repeater2.Items.Count > 1;
             }
            }

Open in new window


Thanks in advance
0

ASP.NET

123K

Solutions

28K

Contributors

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications