GridView and UpdatePanel - preserving the same perspective

Assistance needed for implementing an UpdatePanel. Here is the grid structure:

  <asp:UpdatePanel ID="UpdatePanel1" runat="server" EnableViewState="false" UpdateMode="Conditional">
         <Triggers>
            <asp:AsyncPostBackTrigger ControlID="DropDownList2" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLIne" Width="294px"></asp:TextBox>
            <br />
            <br />
            <asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
                BackColor="#FFFFCC" Width="100%" AutoGenerateSeletButton="True" 
                BorderWidth="1px" EnableSortingAndPagingCallbacks="True" 
                onselectedIndexchanging="GridView1_SelectedIndexChanging" 
                on_SelectedIndexChanged="GridView1_SelectedIndexChanged">
                <Columns>
                    <asp:BoundField DataField="name_disk" HeaderText="Disk Name" SortExpression="disk_name" />
                        <asp:BoundField DataField="folder" HeaderText="Folder" SortExpression="folder" />
                        <asp:BoundField DataField="file_namew" HeaderText="File Name" SortExpression="filename" />
                        <asp:BoundField DataField="duration_time" HeaderText="Duration Time" SortExpression="duration_time" />
                        <asp:BoundField DataField="size" HeaderText="Size" SortExpression="size" />
                        <asp:BoundField DataField="creation_date" HeaderText="Creation Date" SortExpression="creation_date" />
                        <asp:BoundField DataField="modification_date" HeaderText="Modification Date" SortExpression="modification_date" />
                        <asp:BoundField DataField="path" HeaderText="Location" SortExpression="location" />
                </Columns>
                <HeaderStyle BackColor="#9A6E71" Font-Size="Medium" />
                <SellectedRowStyle BackColor="Red" />
            </asp:GridView>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="GridView1" EventName="SelectedIndexChanging" />
        </Triggers>
    </asp:UpdatePanel>

When selecting a row, it should update and refresh the UpdatePanel. The method in question:

 public bool getData(int diskNumber)
    {

        string connectionString = "data source=localhost ;initial catalog=archiwizacjatvs;user id=root;password=wsti";
        MySqlConnection conn = new MySqlConnection(connectionString);
        try
        {
            conn.Open();
            MySqlDataAdapter dataAdapter = new MySqlDataAdapter("select name_disk, folder, file_name, duration_time, size, creation_date, modification_date, path from archive where name_disk='" + DropDownList2.SelectedValue.ToString() + "'", conn);
            DataTable table = new DataTable();
            dataAdapter.Fill(table);
            DataTableReader dataReader = table.CreateDataReader();

            if (table.Rows.Count > 0)
            {
                GridView1.DataSource = table;
                GridView1.DataBind();
                conn.Close();
            }
            else
            {
                TextBox2.Text = "Table is empty!";
            }
            conn.Close();

        }
        catch (Exception ex)
        {
            TextBox2.Text = ex.ToString();
        }
        return true;
    }

protected void Page_Load(object sender, EventArgs e)
{
    // code here to load initial data into DropDownList2
}

protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        getData(DropDownList2.SelectedIndex);
    }

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView1.SelectedIndex =  e.NewSelectedIndex;
        TextBox2.Text = GridView1.SelectedIndex.ToString();
    }

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        getData(DropDownList2.SelectedIndex);
    }

The current behavior is inconsistent - it works on first select or sometimes not at all. Refreshing the page (F5) multiple times seems to fix the issue temporarily. What changes are recommended?

Answer №1

Setting EnableViewState="false" can cause issues with the display of Gridview Data after a button click due to the ViewState not being maintained during a page PostBack. Removing this code from the updatepanel will resolve the problem.

Additionally, adding a condition in the page_load function under !IsPostBack will ensure that the data is retrieved properly:

protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
string connectionString = "data source=localhost ;initial catalog=archiwizacjatvs;user id=user;password=password";
MySqlConnection conn = new MySqlConnection(connectionString);
try {
conn.Open();
MySqlDataAdapter dadapter = new MySqlDataAdapter("select * from archiwum order by nazwa_dysku DESC", conn);
DataTable tablica = new DataTable();
dadapter.Fill(tablica);
DataTableReader datatablereader = tablica.CreateDataReader();
DataRow row = tablica.Rows[0];
for (int i = 1; i <= Convert.ToInt64(row[1]); i++) {
DropDownList2.Items.Add(i.ToString());
}
conn.Close();
} catch (Exception ex) {
TextBox2.Text = ex.ToString();
}
}
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for object destructuring not functioning properly in styles?

Why is it that the HTMLelement is considered an object, while the style is also an object, yet this code fails to work as expected? When I remove destructuring, everything functions properly, so I am curious to understand the underlying reason behind thi ...

Ordering items online as a guest or anonymous user on the ASP.NET CORE online shop platform

I'm working on creating an e-commerce website where I'd like to offer customers the option to make purchases without having to create an account, allowing them to checkout as a Guest or anonymous user. Do you have any suggestions for how I can im ...

Display the count of rows from multiple results in a textbox when the program is run

I recently developed a simple data archiving program in C#. The program interface is displayed in the image below. https://i.sstatic.net/cbiaT.png The main functionality of the program is that when a button is clicked, a message is displayed in the large ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

Enhancing Embedded Lists Within Mongodb

Seeking help with the mongodb syntax to update a specific item within a document's list. Take this sample document for instance. Let's say I need to modify the StartTime for id 524725e61788d8078c900afb { "_id": { "$oid": "524725e61788d8078c9 ...

Error 500: Internal Server Issue Detected during AJAX Request in Laravel

I am having issues with fetching dependent select items using an ajax call. I want to display related 'groups' after selecting a 'class', but I keep getting a 500 internal server error in my console. Can someone please assist me in achi ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

Collaborative information within an ASP.NET web solution

In my ASP.NET application, I currently retrieve data stored on disk for each request, resulting in multiple reads. To optimize this process, I aim to store the loaded data in memory. Since all requests seek the same data, a shared in-memory cache seems ide ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Extracting ng-template Content into a Variable from the Source

I am trying to save the contents of my template into a variable. Here is how my current code looks: HTML <script type="text/ng-template" id="a.html" src="templates/a.html"></script> JS vm.template = $templateCache.get('a.html'); c ...

Ways to modify the color of the legend text in a HighChart graph

Click here https://i.sstatic.net/iuPs4.png I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', ...

Implementing a function as the `data-*` attribute for an element in Angular 6

I have a question about my component.ts file: import { Component, OnInit, AfterViewInit, ElementRef, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { environment } from '../../../enviro ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

Establish and oversee remote connections for a variety of devices

I have a unique setup where I am using a cross domain and PHP server to retrieve user information when they log in. On my website, I incorporate PHP code that includes: session_start(); After a successful login, I declare the user information as follows: ...

Are you interested in creating dynamic tables/models with Sequelize?

Currently, I am exploring a theoretical question before diving into the implementation phase. The scenario is as follows: In my application, users have the ability to upload structured data such as Excel, CSV files, and more. Based on specific requirement ...

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

Unusual navigation patterns in Angular

https://i.sstatic.net/kdh4A.png My Mean app is set up with the Angular app residing in the '/dashboard' path. The home page of the app works fine. Reloading the app returns the page it was on. Even routes with '/dashboard/anything/anything& ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

Smooth transitions: How AJAX calls to PHP chats revolutionize page navigation

When I click the "send button," the page automatically scrolls to the top, which is not the expected behavior. Any suggestions on how to fix this? I've already tried using animations and return false, but nothing seems to be working. Check out the JSF ...

Transform JSON data into a C# class with dual Dictionary attributes

Currently, I am in the process of creating an app using Xamarin and I have a straightforward JSON file consisting of objects that I want to deserialize all at once into my C# Class within my domain. (I am relying on the Newtonsoft Json.NET Framework) Each ...