[Solved] ASP.Net Error: System.Web.UI.WebControls.GridView.SelectedRow.get returned null

lingers
 
on Sep 17, 2021 05:01 PM
Sample_993337.zip
596 Views

I have this gridview on my aspx page.I have 4 column ,id,posino,rev and status.What i want is that if rev value is > o the status should be 'used' else the status should 'new' but i am having this error

System.Web.UI.WebControls.GridView.SelectedRow.get returned null

Server Error in '/WebSite6' Application.


Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error:

Line 75:             TableCell statusCell = e.Row.Cells[3];
Line 76:             
Line 77:             int r1 = Convert.ToInt32(avDetails.SelectedRow.Cells[2].Text);
Line 78: 
Line 79:             if (r1 > 100)

Source File: c:\Users\hp\Documents\Visual Studio 2010\WebSites\WebSite6\gridcontinue.aspx.cs    Line: 77 Stack Trace:

My code

CREATE TABLE [dbo].[cylinde](
[id] [int] NULL,
[posino] [nvarchar](50) NULL,
[pid] [nvarchar](50) NULL,
[Rev] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[cylinde] ([id], [posino], [pid], [Rev]) VALUES (1, N'A101', N'206', N'0')
GO
INSERT [dbo].[cylinde] ([id], [posino], [pid], [Rev]) VALUES (2, N'A102', N'206', N'101')
GO
INSERT [dbo].[cylinde] ([id], [posino], [pid], [Rev]) VALUES (3, N'A103', N'206', N'0')
GO
INSERT [dbo].[cylinde] ([id], [posino], [pid], [Rev]) VALUES (4, N'A104', N'206', N'200')
GO

 

<div>
    <div id="dialog" style="display: none" align="center">
        <span id="lblMessage"></span>
    </div>
    <asp:GridView ID="avDetails"
        runat="server" AutoGenerateColumns="False" Font-Names="Candara"
        Font-Size="14px" DataKeyNames="pid" Width="24%" Style="margin-bottom: 0px"
        CssClass="grid" CellPadding="2" ForeColor="#333333" GridLines="None" Font-Bold="True"
        OnRowDataBound="OnRowDataBound">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="id" HeaderText="ID" />
            <asp:BoundField DataField="posino" HeaderText="POSINO" />
            <asp:BoundField DataField="Rev" HeaderText="REV" />
            <asp:BoundField DataField="" HeaderText="STATUS" />
            <asp:TemplateField HeaderText="USE">
                <ItemTemplate>
                    <asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="OnChckedChanged" AutoPostBack="True" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
    <script type="text/javascript">
        function ShowPopup(message) {
            $("#lblMessage").html(message);
            $("#dialog").dialog({
                modal: true,
                title: "Message Alert",
                width: 350,
                height: 160
            });
        }
        $(function () {
            $(window).on('popstate', function () {
                $('#myModal').modal('hide');
            });
        });
    </script>
</div>

 

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindUserDetails1();
    }
}

protected void BindUserDetails1()
{
    string constr1 = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con1 = new SqlConnection(constr1))
    {
        using (SqlDataAdapter sda1 = new SqlDataAdapter("SELECT * from cylinde", con1))
        {

            using (DataTable dt1 = new DataTable())
            {
                sda1.Fill(dt1);
                avDetails.DataSource = dt1;
                avDetails.DataSource = dt1;
                avDetails.DataBind();
            }
        }
    }
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string id = e.Row.Cells[2].Text;
        string[] cylinders = GetAcceptedCylinder(id).Replace("[", "").Replace("]", "").Split(',');
        CheckBox chkSelect = e.Row.FindControl("chkSelect") as CheckBox;
        if (cylinders.Contains("'" + e.Row.Cells[1].Text + "'"))
        {
            chkSelect.Checked = true;
        }
        else
        {
            chkSelect.Checked = false;
        }


        TableCell revCell = e.Row.Cells[2];
        TableCell statusCell = e.Row.Cells[3];

        int r1 = Convert.ToInt32(avDetails.SelectedRow.Cells[2].Text);

        if (r1 > 100)

        {
            statusCell.Text = "Used";
        }
        else
        {
            statusCell.Text = "New";
        }

    }
}
protected void OnChckedChanged(object sender, EventArgs e)
{
    CheckBox chk = (CheckBox)sender;
    GridViewRow row = (GridViewRow)chk.NamingContainer;

    string number = row.Cells[1].Text;
    string pid = "206";

    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {
        string acceptedCylinder = GetAcceptedCylinder(pid);
        if (chk.Checked)
        {
            if (acceptedCylinder == "[]")
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", "['" + number.Trim() + "']");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Inserted successfully.');", true);
            }
            else
            {
                List<string> cylinderNo = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(',').ToList();
                cylinderNo.Add(number);
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", "['" + string.Join("','", cylinderNo.Distinct()) + "']");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Updated Successfully.');", true);
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(acceptedCylinder))
            {
                List<string> cylinderNo = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(',').ToList();
                cylinderNo.Remove(number);
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206' ", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", cylinderNo.Distinct().Count() > 0 ? "['" + string.Join("','", cylinderNo.Distinct()) + "']" : "[]");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Deleted Successfully.');", true);
            }
        }
    }
}

private string GetAcceptedCylinder(string pid)
{
    string acceptCylinder = "";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT cylinders FROM issuesheet WHERE pid=@pid ";
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@pid", 206);
            con.Open();
            acceptCylinder = Convert.ToString(cmd.ExecuteScalar());
            con.Close();
        }
    }

    return acceptCylinder;
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 18, 2021 02:09 AM
on Sep 18, 2021 02:10 AM

Hi lingers,

Check this example. Now please take its reference and correct your code.

HTML

<div>
    <div id="dialog" style="display: none" align="center">
        <span id="lblMessage"></span>
    </div>
    <asp:GridView ID="avDetails"
        runat="server" AutoGenerateColumns="False" Font-Names="Candara"
        Font-Size="14px" DataKeyNames="pid" Width="24%" Style="margin-bottom: 0px"
        CssClass="grid" CellPadding="2" ForeColor="#333333" GridLines="None" Font-Bold="True"
        OnRowDataBound="OnRowDataBound">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="id" HeaderText="ID" />
            <asp:BoundField DataField="posino" HeaderText="POSINO" />
            <asp:BoundField DataField="Rev" HeaderText="REV" />
            <asp:BoundField DataField="" HeaderText="STATUS" />
            <asp:TemplateField HeaderText="USE">
                <ItemTemplate>
                    <asp:CheckBox ID="chkSelect" runat="server" OnCheckedChanged="OnChckedChanged" AutoPostBack="True" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
    <script type="text/javascript">
        function ShowPopup(message) {
            $("#lblMessage").html(message);
            $("#dialog").dialog({
                modal: true,
                title: "Message Alert",
                width: 350,
                height: 160
            });
        }
        $(function () {
            $(window).on('popstate', function () {
                $('#myModal').modal('hide');
            });
        });
    </script>
</div>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindUserDetails1();
    }
}

protected void BindUserDetails1()
{
    string constr1 = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con1 = new SqlConnection(constr1))
    {
        using (SqlDataAdapter sda1 = new SqlDataAdapter("SELECT * from cylinde", con1))
        {
            using (DataTable dt1 = new DataTable())
            {
                sda1.Fill(dt1);
                avDetails.DataSource = dt1;
                avDetails.DataSource = dt1;
                avDetails.DataBind();
            }
        }
    }
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int id = Convert.ToInt32(e.Row.Cells[2].Text);
        string[] cylinders = GetAcceptedCylinder(id.ToString()).Replace("[", "").Replace("]", "").Split(',');
        CheckBox chkSelect = e.Row.FindControl("chkSelect") as CheckBox;
        if (cylinders.Contains("'" + e.Row.Cells[1].Text + "'"))
        {
            chkSelect.Checked = true;
        }
        else
        {
            chkSelect.Checked = false;
        }
        TableCell statusCell = e.Row.Cells[3];

        if (id > 100)
        {
            statusCell.Text = "Used";
        }
        else
        {
            statusCell.Text = "New";
        }
    }
}

protected void OnChckedChanged(object sender, EventArgs e)
{
    CheckBox chk = (CheckBox)sender;
    GridViewRow row = (GridViewRow)chk.NamingContainer;

    string number = row.Cells[1].Text;
    string pid = "206";

    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {
        string acceptedCylinder = GetAcceptedCylinder(pid);
        if (chk.Checked)
        {
            if (acceptedCylinder == "[]")
            {
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", "['" + number.Trim() + "']");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Inserted successfully.');", true);
            }
            else
            {
                List<string> cylinderNo = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(',').ToList();
                cylinderNo.Add(number);
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", "['" + string.Join("','", cylinderNo.Distinct()) + "']");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Updated Successfully.');", true);
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(acceptedCylinder))
            {
                List<string> cylinderNo = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(',').ToList();
                cylinderNo.Remove(number);
                using (SqlCommand cmd = new SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206' ", con))
                {
                    cmd.Parameters.AddWithValue("@cylinders", cylinderNo.Distinct().Count() > 0 ? "['" + string.Join("','", cylinderNo.Distinct()) + "']" : "[]");
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('Record Deleted Successfully.');", true);
            }
        }
    }
}

private string GetAcceptedCylinder(string pid)
{
    string acceptCylinder = "";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT cylinders FROM issuesheet WHERE pid=@pid ";
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@pid", 206);
            con.Open();
            acceptCylinder = Convert.ToString(cmd.ExecuteScalar());
            con.Close();
        }
    }

    return acceptCylinder;
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindUserDetails1()
    End If
End Sub

Protected Sub BindUserDetails1()
    Dim constr1 As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con1 As SqlConnection = New SqlConnection(constr1)
        Using sda1 As SqlDataAdapter = New SqlDataAdapter("SELECT * from cylinde", con1)
            Using dt1 As DataTable = New DataTable()
                sda1.Fill(dt1)
                avDetails.DataSource = dt1
                avDetails.DataSource = dt1
                avDetails.DataBind()
            End Using
        End Using
    End Using
End Sub

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim id As Integer = Convert.ToInt32(e.Row.Cells(2).Text)
        Dim cylinders As String() = GetAcceptedCylinder(id.ToString()).Replace("[", "").Replace("]", "").Split(","c)
        Dim chkSelect As CheckBox = TryCast(e.Row.FindControl("chkSelect"), CheckBox)
        If cylinders.Contains("'" & e.Row.Cells(1).Text & "'") Then
            chkSelect.Checked = True
        Else
            chkSelect.Checked = False
        End If
        Dim statusCell As TableCell = e.Row.Cells(3)
        If id > 100 Then
            statusCell.Text = "Used"
        Else
            statusCell.Text = "New"
        End If
    End If
End Sub

Protected Sub OnChckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim chk As CheckBox = CType(sender, CheckBox)
    Dim row As GridViewRow = CType(chk.NamingContainer, GridViewRow)
    Dim number As String = row.Cells(1).Text
    Dim pid As String = "206"
    Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

    Using con As SqlConnection = New SqlConnection(constring)
        Dim acceptedCylinder As String = GetAcceptedCylinder(pid)
        If chk.Checked Then
            If Equals(acceptedCylinder, "[]") Then
                Using cmd As SqlCommand = New SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con)
                    cmd.Parameters.AddWithValue("@cylinders", "['" & number.Trim() & "']")
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using

                ClientScript.RegisterStartupScript([GetType](), "Popup", "ShowPopup('Record Inserted successfully.');", True)
            Else
                Dim cylinderNo As List(Of String) = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(","c).ToList()
                cylinderNo.Add(number)

                Using cmd As SqlCommand = New SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206'", con)
                    cmd.Parameters.AddWithValue("@cylinders", "['" & String.Join("','", cylinderNo.Distinct()) & "']")
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using

                ClientScript.RegisterStartupScript([GetType](), "Popup", "ShowPopup('Record Updated Successfully.');", True)
            End If
        Else

            If Not String.IsNullOrEmpty(acceptedCylinder) Then
                Dim cylinderNo As List(Of String) = acceptedCylinder.Replace("[", "").Replace("]", "").Replace("'", "").Split(","c).ToList()
                cylinderNo.Remove(number)

                Using cmd As SqlCommand = New SqlCommand("UPDATE issuesheet SET cylinders = @cylinders where pid='206' ", con)
                    cmd.Parameters.AddWithValue("@cylinders", If(cylinderNo.Distinct().Count() > 0, "['" & String.Join("','", cylinderNo.Distinct()) & "']", "[]"))
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using

                ClientScript.RegisterStartupScript([GetType](), "Popup", "ShowPopup('Record Deleted Successfully.');", True)
            End If
        End If
    End Using
End Sub

Private Function GetAcceptedCylinder(ByVal pid As String) As String
    Dim acceptCylinder As String = ""
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "SELECT cylinders FROM issuesheet WHERE pid=@pid "
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@pid", 206)
            con.Open()
            acceptCylinder = Convert.ToString(cmd.ExecuteScalar())
            con.Close()
        End Using
    End Using

    Return acceptCylinder
End Function

Screenshot