valdiate gridview data using asp.net c# code behind on button click

RAVI 1,056 Reputation points
2024-09-22T13:37:28.3666667+00:00

Hello

This Is my MS sql data

/****** Object:  Table [dbo].[Table_11]    Script Date: 09/22/2024 19:00:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Table_11](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ItemName] [varchar](500) NULL,
	[UOM] [nchar](10) NULL,
	[Required_Quantity] [float] NULL,
	[Stock_Quantity] [float] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Table_11] ON
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (281, N'APPLE', N'KGS       ', 3, 4)
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (282, N'MANGO', N'PIECE     ', 2, 5)
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (283, N'BANANA', N'KGS       ', 4, 10)
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (284, N'ITEM 3', N'MTR       ', 12, 20)
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (285, N'APPLE', N'KGS       ', 6, 4)
INSERT [dbo].[Table_11] ([ID], [ItemName], [UOM], [Required_Quantity], [Stock_Quantity]) VALUES (286, N'ITEM 4', N'MTR       ', 3, 13)
SET IDENTITY_INSERT [dbo].[Table_11] OFF

This Is My aspx with masterpage

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default10.aspx.cs" Inherits="Default10" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button ID="Button4" runat="server" AccessKey="R" BackColor="Transparent" BorderColor="Black"
        BorderStyle="Dotted" BorderWidth="1px" Font-Bold="True" Font-Names="Calibri"
        Font-Size="10pt" ForeColor="#FFFFFF" Height="40px" OnClick="Button4_Click1" Style="background-image: url(images/btn_5.png);
        vertical-align: top" TabIndex="24" Text="2-SAVE" ValidationGroup="edccde" Width="96px" /><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellSpacing="3"
        Font-Bold="True" Font-Names="Palatino Linotype" Font-Size="11pt" ForeColor="Black"
        
        Width="999px">
        <Columns>
            <asp:TemplateField HeaderText="ITEM NAME">
                <ItemTemplate>
                    <asp:Label ID="L1" runat="server" Text='<%# Bind("ItemName") %>'></asp:Label>
                </ItemTemplate>
                <ControlStyle Width="90px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            
            <asp:TemplateField HeaderText="UOM">
                <ItemTemplate>
                    <asp:Label ID="L2" runat="server" Text='<%# Bind("UOM") %>'></asp:Label>
                </ItemTemplate>
                <ControlStyle Width="90px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            
            
               <asp:TemplateField HeaderText="REQUIRED QTY">
                <ItemTemplate>
                    <asp:TextBox ID="Txt_RQ" runat="server" Text='<%# Bind("Required_Quantity") %>'></asp:TextBox>
                </ItemTemplate>
                <ControlStyle Width="90px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField>
            
               <asp:TemplateField HeaderText="STOCK QTY">
                 <ItemTemplate>
                    <asp:Label ID="L3" runat="server" Text='<%# Bind("Stock_Quantity") %>'></asp:Label>
                </ItemTemplate>
                <ControlStyle Width="90px" />
                <HeaderStyle ForeColor="Red" />
            </asp:TemplateField> 
            
        </Columns>
    </asp:GridView>
</asp:Content>


This is My asp.net C# Page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Globalization;
public partial class Default10 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {


            DataTable zdtu = new DataTable();
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["invConnectionString"].ConnectionString);
            con.Open();
            SqlCommand cmmd1 = new SqlCommand("select * from Table_11", con); 
            SqlDataAdapter ada = new SqlDataAdapter(cmmd1);
            ada.Fill(zdtu);
            GridView1.DataSource = zdtu;
            GridView1.DataBind();           
            con.Close();
            con.Dispose();



        }
    }
    protected void Button4_Click1(object sender, EventArgs e)
    {

    }
}

On load it shows data perfect i want to check validation and show alert required quantity is greater then stock quantity

for example see in whole gridview apple has two time one time it required is 3 and one time its required is 6 now on button click it has to show alert check required quantity if user enter instead of 6 as 1 it should accpet coz we have 4 quantity

how to do this validation using asp.net c# code behind on button click

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,474 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. SurferOnWww 2,741 Reputation points
    2024-09-23T02:31:35.4666667+00:00

    On load it shows data perfect i want to check validation and show alert required quantity is greater then stock quantity

    I suggest that you show the "alert" by changing a background-color of the row where required quantity is greater than stock quantity, as shown below:

    enter image description here

    Below is sample code which shows the above GridView.

    Note that you have to modify the code if you want to show the "alert" only on button click. I believe that you will be able to do so easily.

    .aspx.cs

    Note that in the event handler for the GridView.RowDataBound event the required quantity and the stock quantity are compared and the background-color of the row is set to yellow if the required quantity is greater than the stock quantity.

    using System;
    using System.Data;
    using System.Web.UI.WebControls;
    
    namespace WebForms1
    {
        public partial class WebForm43 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DataRowView drv = (DataRowView)e.Row.DataItem;
                    if ((Int16)drv["UnitsOnOrder"] > (Int16)drv["UnitsInStock"]) 
                    {
                        e.Row.CssClass = "style1";
                    }
                }
            }
        }
    }
    

    .aspx

    <%@ Page Language="C#" AutoEventWireup="true"
        CodeBehind="WebForm43.aspx.cs"
        Inherits="WebForms1.WebForm43" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            .style1 {
                background-color:yellow;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:SqlDataSource ID="SqlDataSource1"
                runat="server"
                ConnectionString="<%$ ConnectionStrings:NORTHWINDConnectionString %>"
                SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock], [UnitsOnOrder] FROM [Products]"></asp:SqlDataSource>
    
            <asp:GridView ID="GridView1" runat="server"
                AutoGenerateColumns="False"
                DataKeyNames="ProductID"
                DataSourceID="SqlDataSource1"
                OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="ProductID"
                        HeaderText="ProductID" InsertVisible="False"
                        ReadOnly="True" SortExpression="ProductID" />
                    <asp:BoundField DataField="ProductName"
                        HeaderText="ProductName" SortExpression="ProductName" />
                    <asp:BoundField DataField="UnitPrice"
                        HeaderText="UnitPrice" SortExpression="UnitPrice" />
                    <asp:BoundField DataField="UnitsInStock"
                        HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                    <asp:BoundField DataField="UnitsOnOrder"
                        HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>
    

    Above uses the Nortwind Products table:

    enter image description here

    0 comments No comments

  2. SurferOnWww 2,741 Reputation points
    2024-09-23T02:55:17.8533333+00:00

    This answer has been deleted because of duplication.

    0 comments No comments

  3. Lan Huang-MSFT 29,251 Reputation points Microsoft Vendor
    2024-09-23T06:52:33.7066667+00:00

    Hi @RAVI,

    You have asked a similar question before, which was achieved by adding a checkbox. For details, please refer to the answer I provided before.

    https://video2.skills-academy.com/en-us/answers/questions/1806153/validate-item-in-entire-gridview-to-check-excess-q

    Based on your current code, I retested an example you can refer to.

    protected void Button4_Click1(object sender, EventArgs e)
    {
        decimal total = 0;
        for (int current = 0; current < GridView1.Rows.Count; current++)
        {
            for (int other = current + 1; other < GridView1.Rows.Count; other++)
            {
                Label compareRow = GridView1.Rows[current].FindControl("L1") as Label;
                Label L3 = GridView1.Rows[current].FindControl("L3") as Label;
                decimal stock = Convert.ToDecimal(L3.Text);
                TextBox qty = GridView1.Rows[current].FindControl("Txt_RQ") as TextBox;
                Label row = GridView1.Rows[other].FindControl("L1") as Label;
                if (compareRow.Text == row.Text)
                {
                    TextBox qty1 = GridView1.Rows[other].FindControl("Txt_RQ") as TextBox;
                    total = Convert.ToDecimal(qty.Text) + Convert.ToDecimal(qty1.Text);
                    if (total > stock)
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + row.Text + "' + 'Inventory shortage!!!');", true);
                    }
                }
            }
        }
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.