When utilizing gridView, the ExecuteReader method will throw an error if the CommandText property has not been

I am encountering an issue with populating a gridView using the ExecuteReader function in my program. Every time I run it, I receive an error message stating "ExecuteReader : CommandText property has not been initialized".

aspx.cs

    private void LoadGrid()
    {
    //creating a list of items to display 
        var stockItems = new List<StockUpdate>();

    //setting up the SQL command to retrieve data from the table

        SqlCommand command = new SqlCommand();

        command.CommandText = dsrFilteredBranches.InsertCommand;
        command.Connection = connection;

        connection.Open();

        SqlDataReader rd = command.ExecuteReader();

    //filling the table with retrieved data
        if (rd.HasRows)
        {
            while (rd.Read())
            {
                stockItems.Add(new StockUpdate
                {
                    BranchCode = rd["BranchCode"].ToString(),
                    StockTakeID = Convert.ToInt32(rd["StockTakeID"].ToString()),
                    Name = rd["Name"].ToString(),
                    Description = rd["Description"].ToString(),
                    StocktakeDate = rd["StocktakeDate"].ToString(),
                    Quantity = Convert.ToInt32(rd["Quantity"].ToString())     
                });
            }
        }

        connection.Close();
        dgvStockTake.DataSource = stockItems;
        dgvStockTake.DataBind();

    }

aspx

<asp:GridView ID="dgvStockTake" runat="server" AutoGenerateColumns="False" CssClass="auto-style8" DataKeyNames="BranchCode">

        <%-- creating editable columns for the gridView --%>        

        <Columns>

        <asp:TemplateField HeaderText="BranchCode">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblBranchCode" Text='<%# Bind("BranchCode") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblID" Text='<%# Bind("StockTakeID") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text='<%# Bind("Name") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Descrption">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblDescription" Text='<%# Bind("Description") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="StockTakeDate">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblStocktakeDate" Text='<%# Bind("StocktakeDate") %>'>
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
                <asp:Textbox runat="server" ID="txtQuantity" CssClass="backColor" Text='<%# Bind("Quantity") %>'>
                </asp:Textbox>
            </ItemTemplate>
        </asp:TemplateField>

        </Columns>

        </asp:GridView>

class

public class StockUpdate
{
    public string BranchCode { get; set; }
    public int StockTakeID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string StocktakeDate { get; set; }
    public int Quantity { get; set; }
}

I attempted to use a SQLDataSource as the gridView's data source but it caused the entire gridView and its HTML code to disappear. This is why I resort to using the DataReader.

Replacing "dsrFilteredBranches.InsertCommand" with my actual SQL command results in an error mentioning that the scalar variable @BranchCode has not been initialized, and I have yet to resolve this problem.

I have spent hours trying to fix this issue and any assistance would be greatly appreciated.

Answer №1

To set parameters for your SqlCommand before executing it, follow these steps:

command.CommandText = dsrFilteredBranches.InsertCommand;

SqlParameter customParameter = new SqlParameter
{
    ParameterName = "@CustomParameter",
    Value = CustomParameterValue
};

command.Parameters.Add(customParameter);

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 impacts should I expect from updating my .NET analyzer's target framework to .NET 5.0?

For my analyzer, I initially utilized .NET Standard 2.0 to target .NET Framework 4.7.2 in the VSIX version. However, I eventually decided to discontinue support for it as it did not offer significant advantages. Now, I am eager to upgrade the supported fra ...

What steps can be taken to avoid an input with a width of 100% from overflowing?

I'm facing an issue that needs to be resolved. Currently, I have a group of div elements arranged in a table-like structure with a row and three columns. When these divs reach a maximum width of 768px, the first column is hidden, leaving only the se ...

Swapping IMG depending on breakpoint in Material-UI

I understand how to adjust styling with breakpoints for various properties like height, width, and font size. However, I am struggling to find examples of switching images based on screen sizes. My goal is to replace an image with a different one dependin ...

Refresh the webpage excluding a single element using AJAX

I'm facing a challenge with an audioplayer on a webpage that needs to keep playing without interruption while navigating. The layout of the page cannot be changed, so simply moving the audio player outside and reloading the content is not an option. ...

Implementing the Audio() Element with JavaScript

I've written the code below, but it's not working properly! When I click on the play button, nothing happens HTML: <button id="play"><img id="playicon" src="img/Polygon 1.svg"></button> JS: I have a variable named 'song0 ...

App interface automatically redirecting user back to login page post-login

Hello, I have been working on Selenium C# and have successfully implemented some methods using pagefactory. However, I am facing an issue where the application opens a new instance of the login page after logging in. How can I ensure that only a single lo ...

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...

The inner DIV cannot be accessed using document.getElementById due to its limited scope

Here is the HTML code below: <Div id="one"> <Div id="two"> </Div> </Div> When trying to access div "two" using "document.getElementById("two")", it returns null. ...

Avoiding the separation of hyphenated words when they overflow on a new line

My code is designed to limit text to two lines and show an ellipsis if there is more content. However, I am facing an issue with hyphenated words like "breath-taking" not being treated as one word. Instead, they are often cut off at the end of the second l ...

Ways to eliminate the relationship between parent and child

I am attempting to create a design featuring a large circle surrounded by smaller circles. The parent element is the large circle, and the small circles are its children. My goal is for any circle to change color to red when hovered over, but if I hover ov ...

Issue with Bootstrap 4 progress bar malfunctioning in popover due to CSS property restrictions within the popover container

The following code functions correctly in the body area: <div class="progress" style="height: 25px;"> <div class="progress-bar" style="width: 30%;" role="progressbar" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"> </div> & ...

Move the accordion slider to the top of the browser

I'm working with an accordion menu that has some long content. To make it more user-friendly, I want to add a slide effect when the accordion items are opened. Right now, if you open the first two menu items, the last item's content is cut off a ...

Looking for a way to make a button glide down to the bottom of a card in a

I need to ensure that the contact button in each card floats to the bottom, regardless of the amount of text within the card. This will create a uniform appearance with all cards having the contact button in the same position. Here is an example of how on ...

Using Django to upload an XML document via an HTML form

When working with Django framework and python scripts to validate XML files, my usual approach involves parsing the XML file located at a specified location using the following code: import xml.etree.ElementTree as ET tree = ET.parse('config.xml&apos ...

What is the best way to make this CSS arrow see-through?

My goal is to achieve this desired outcome: https://i.sstatic.net/4eTpE.png Currently, I have the following (focusing only on the left element for now): https://i.sstatic.net/nUFp1.png I am struggling to make the left arrow transparent and I can't ...

Expanding a list in AngularJS: Implementing a scrollbar for a seamless user experience

I need assistance in creating a layout using AngularJS and angular-material that includes a vertical scrollbar when necessary: <div layout="column"> <div> <!-- Occupies 80% of window browser --> <md-list> <md-l ...

I am attempting to secure a webpage with a password using JavaScript

I've been working on adding password protection to my webpage at , with the goal of allowing users to enter the password once per session. However, I've encountered an issue: if a user cancels out of the initial prompt or enters the wrong passwor ...

What is the process for adding tailwind CSS via npm?

Before, I was including Tailwind using a CDN. Now, I have installed it with npm and all three .css files are included, but the styles are not appearing in my HTML document. Here is the directory structure and a link to style.css The content of tailwind.c ...

Textarea generated on-the-fly without any assigned value

My goal is to enable users to edit the text within a paragraph on a website. I am attempting to replace the <p> tags with <textarea> tags using the .replaceWith() function. However, when I try to retrieve the value of the textarea, it comes bac ...

determining the user's position within the <s:select> element

I have a dropdown select tag in my code with a list of countries. I want the user's country to be auto-selected when they access the page. This is the JSP code snippet: <s:select name="dropdown" list="countries" listKey="value" listV ...