Multiple select command in a grid view - c#

<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CssClass="table-bordered table-hover table-responsive table" BackColor="White" BorderColor="White" CellPadding="3" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowSelectButton="True" ControlStyle-CssClass="accept" SelectText="Accept" ControlStyle-ForeColor="Green" >
<ControlStyle CssClass="accept" ForeColor="Green"></ControlStyle>
</asp:CommandField>
<asp:CommandField ShowSelectButton="True" ControlStyle-CssClass="reject" SelectText="Reject" ControlStyle-ForeColor="Red" >
<ControlStyle CssClass="reject" ForeColor="Red"></ControlStyle>
</asp:CommandField>
<asp:BoundField HeaderText="Status" />
<asp:BoundField DataField="first_name" HeaderText="First name" SortExpression="first_name" />
<asp:BoundField DataField="last_name" HeaderText="Last name" SortExpression="last_name" />
<asp:BoundField DataField="c_email" HeaderText="Email" SortExpression="c_email" />
<asp:BoundField DataField="contact" HeaderText="Contact" SortExpression="contact" />
<asp:BoundField DataField="licenseno" HeaderText="License no" SortExpression="licenseno" />
<asp:BoundField DataField="v_name" HeaderText="Vehicle name" SortExpression="v_name" />
<asp:BoundField DataField="v_company" HeaderText="Company" SortExpression="v_company" />
<asp:BoundField DataField="v_plate" HeaderText="Plate no" SortExpression="v_plate" />
<asp:BoundField DataField="wheeler" HeaderText="Wheeler" SortExpression="wheeler" />
<asp:BoundField DataField="damage_Details" HeaderText="Damage details" SortExpression="damage_Details" />
<asp:BoundField DataField="street" HeaderText="Street" SortExpression="street" />
<asp:BoundField DataField="landmark" HeaderText="Landmark" SortExpression="landmark" />
<asp:BoundField DataField="pincode" HeaderText="Pincode" SortExpression="pincode" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#752c82" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedRow.Cells[2].Text = "Accepted";
string msg = "ACCEPTED";
Session["c_email"] = GridView1.SelectedRow.Cells[5].Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Status values(#email,#c_email,#status)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["c_email"].ToString());
cmd.Parameters.AddWithValue("#email", Session["mechanic"].ToString());
cmd.Parameters.AddWithValue("#status", msg.ToString());
cmd.ExecuteNonQuery();
Label1.Text = "You need to reach the customer within one hour and provide the needful service.";
con.Close();
}
I have a grid view that contains two command fields with 2 selection button. I want the button as Accept and Reject on my page. But I am unable to find out how to code it's working.
I have coded for one command field on selectedIndexChanged but how to code for the second command field. Please help me out.

Related

how to get cell value from gridview

protected void CovidSelfDecleartionDeatils_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
ShowallRecord();
if (e.CommandArgument != "")
{
int Index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName=="Select")
{
DataTable dt_main = new DataTable();
dt_main = (DataTable)ViewState["ReportData"];
GridViewRow clickedRow = CovidSelfDecleartionDeatils.Rows[Index];
Session["Filepath"] = clickedRow.Cells[9].Text;
//Session["Filepath"] = CovidSelfDecleartionDeatils.Rows[Index].FindControl("FilePath");
Session["Filepath1"] = CovidSelfDecleartionDeatils.DataKeys[Index]["Filepath"].ToString();
string filepath = Session["Filepath"].ToString();
//DataGridViewSelectedRowCollection rows = dataGridView1.SelectedRows;
//string val = (string)rows[2].Cells["Late_Time"].Value;
}
}
}
catch
{
}
}
<asp:GridView ID="CovidSelfDecleartionDeatils" runat="server" DataKeyNames="EmployeeCode" AutoGenerateColumns="False"
BackColor="#333333" CellPadding="5" CellSpacing="3" ForeColor="Black" Width="100%" Height="300px" OnRowCommand="CovidSelfDecleartionDeatils_RowCommand" >
<Columns>
<%-- <asp:BoundField DataField="InitiateMPPId" HeaderText="InitiateMPPId" >
<HeaderStyle HorizontalAlign="Center" />
</asp:BoundField>--%>
<asp:BoundField DataField="EmployeeCode" HeaderText="EmployeeCode" ItemStyle-HorizontalAlign="Left" Visible="false"
HeaderStyle-HorizontalAlign="Left" ControlStyle-BorderStyle="None" ItemStyle-CssClass="per10"
HeaderStyle-CssClass="header-center">
</asp:BoundField>
<%-- <asp:BoundField DataField="EmployeeCode" HeaderText="EmployeeCode" ItemStyle-HorizontalAlign="Left" Visible="false"
HeaderStyle-HorizontalAlign="Left" ControlStyle-BorderStyle="None" ItemStyle-CssClass="per10"
HeaderStyle-CssClass="header-center">
</asp:BoundField>--%>
<asp:BoundField DataField="EmpName" HeaderText="Employee" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" >
</asp:BoundField>
<asp:BoundField DataField="Decleartion_Date" HeaderText="Date Decleartion" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" DataFormatString="{0:dd-MM-yyyy}" >
</asp:BoundField>
<asp:BoundField DataField="Ferver" HeaderText="Ferver" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Cough" HeaderText="Cough" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="Breathlessness" HeaderText="Breathlessness" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OtherDiseases" HeaderText="OtherDiseases" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-CssClass="per50" ItemStyle-Height="25" HeaderStyle-Height="25" HeaderStyle-CssClass="header-center" HeaderStyle-Wrap="true"/>
<asp:BoundField DataField="FileName" HeaderText="FileName" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-CssClass="per50" ItemStyle-Height="25" HeaderStyle-Height="25" HeaderStyle-CssClass="header-center" HeaderStyle-Wrap="true" Visible="false" />
<asp:BoundField DataField="DeclarationID" HeaderText="DeclarationID" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-CssClass="per50" ItemStyle-Height="25" HeaderStyle-Height="25" HeaderStyle-CssClass="header-center" HeaderStyle-Wrap="true" Visible="false" />
<asp:BoundField DataField="FilePath" HeaderText="FilePathfordownload" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-CssClass="per50" ItemStyle-Height="25" HeaderStyle-Height="25" HeaderStyle-CssClass="header-center" HeaderStyle-Wrap="true" Visible="false" />
<asp:BoundField DataField="ContactwithCovid" HeaderText="Incontact with covid patient Last(14) days" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" ItemStyle-CssClass="per50" ItemStyle-Height="25" HeaderStyle-Height="25" HeaderStyle-Width="15%" HeaderStyle-CssClass="header-center" HeaderStyle-Wrap="true"/>
<%--<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="btn_delete_record"
Width="20px" Height="20px" runat="server" ImageUrl="~/Content/Images/NewIcons/PDF.png" />
</ItemTemplate>
</asp:TemplateField>--%>
<asp:ButtonField CommandName="Select" ControlStyle-CssClass="button" ButtonType="Image" ImageUrl="~/Content/Images/NewIcons/PDF.png"
ItemStyle-Width="5px" HeaderText="Download Attachment" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="TravelDate" HeaderText="TravelDate" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" DataFormatString="{0:dd-MM-yyyy}" />
<asp:BoundField DataField="StateName" HeaderText="StateName" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#5e5d5d" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="Gray" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
what wrong in my showing excetion " Object reference is not set" when i am saving value in session
remove visible=false and define new css class like
.donotshow { display: none; }
and add it HeaderStyle-CssClass and ItemStyle-CssClass

How to send message on different page using the select command in grid view?

<div class="row" style="color:black">
<div class="col">
<asp:GridView ID="GridView1" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CssClass="table-bordered table-hover table-responsive table" BackColor="White" BorderColor="White" CellPadding="3" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Accept" ControlStyle-ForeColor="Green" />
<asp:CommandField ShowDeleteButton="true" DeleteText="Reject" ControlStyle-ForeColor="Red"/>
<asp:BoundField DataField="first_name" HeaderText="first_name" SortExpression="first_name" />
<asp:BoundField DataField="last_name" HeaderText="last_name" SortExpression="last_name" />
<asp:BoundField DataField="c_email" HeaderText="c_email" SortExpression="c_email" />
<asp:BoundField DataField="contact" HeaderText="contact" SortExpression="contact" />
<asp:BoundField DataField="licenseno" HeaderText="licenseno" SortExpression="licenseno" />
<asp:BoundField DataField="v_name" HeaderText="v_name" SortExpression="v_name" />
<asp:BoundField DataField="v_company" HeaderText="v_company" SortExpression="v_company" />
<asp:BoundField DataField="v_plate" HeaderText="v_plate" SortExpression="v_plate" />
<asp:BoundField DataField="wheeler" HeaderText="wheeler" SortExpression="wheeler" />
<asp:BoundField DataField="damage_Details" HeaderText="damage_Details" SortExpression="damage_Details" />
<asp:BoundField DataField="street" HeaderText="street" SortExpression="street" />
<asp:BoundField DataField="landmark" HeaderText="landmark" SortExpression="landmark" />
<asp:BoundField DataField="pincode" HeaderText="pincode" SortExpression="pincode" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#752c82" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Tazzac.mdf;Integrated Security=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT CustomerReg.first_name, CustomerReg.last_name, CustomerReg.c_email, CustomerReg.contact, CustomerReg.licenseno, vehicle_detail.v_name, vehicle_detail.v_company, vehicle_detail.v_plate, vehicle_detail.wheeler, ServiceInfo.damage_Details, ServiceInfo.street, ServiceInfo.landmark, ServiceInfo.pincode FROM CustomerReg CROSS JOIN vehicle_detail INNER JOIN ServiceInfo ON CustomerReg.c_email = ServiceInfo.c_email AND vehicle_detail.v_plate = ServiceInfo.v_plate WHERE (ServiceInfo.email = #email)">
<SelectParameters>
<asp:SessionParameter Name="email" SessionField="mechanic" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</div>
I have taken two select commands in my grid view, one is accept and other is reject. So, I need to display message on different page not the same page. As the user clicks on accept it should display message as accepted and on reject it should display reject. But i am not getting away how to do it as I have not taken template in grid view. So I humbly request for help in it.
Since your question is only about "send a message on a different page using select command" One way to achieve this is using session variables within C# .NET application.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
String strStatus = "Accepted";
Session["key1"] = strStatus;
string BrowserSettings = "status=no,toolbar=no,menubar=no,location=no,resizable=no," +
"titlebar=no, addressbar=no, width=600 ,height=750";
string URL = "StatusWebForm.aspx";
string scriptText = "window.open('" + URL + "','_blank','" + BrowserSettings + "');";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ClientScript1", scriptText, true);
}
This ScriptManager concept was answered by Mahantesh, so I want to give him credit for that.
On second WebForm (.aspx.cs) page where you want to display the message, add a Label and Page_Load event.
public partial class StatusWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String strStatus = (String)Session["key1"];
lblStatus.Text = strStatus;
}
}

Save CheckBox Values in GridView to Database. ASP.NET

i am developing webform with gridview. I have a problem, the value of checkbox doesn't save in the table. I've tried everything nothing is working. After i press a button, value doesn't store.
And as you can see in my code, i don't use id for unidentified of each particular row, instead id i use foreach
protected void Button_Submit_Onclick(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView2.Rows)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
bool private1 = (row.FindControl("CheckBox1") as CheckBox).Checked;
SqlCommand cmd = new SqlCommand("insert into DetailCosts(private) values(#private1)", con);
if (private1 == true)
{
cmd.Parameters.Add(new SqlParameter("#private1", SqlDbType.Bit));
cmd.Parameters["#private1"].Value = 1;
//cmd.Parameters.Add("#private1", SqlDbType.Bit).Value = 1;
}
else
{
cmd.Parameters.Add(new SqlParameter("#private1", SqlDbType.Bit));
cmd.Parameters["#private1"].Value = 0;
//cmd.Parameters.Add("#private1", SqlDbType.Bit).Value = 0;
}
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}}
and there is a code with my Gridview:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" DataKeyNames="recordid">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="recordid" HeaderText="recordid" SortExpression="recordid">
</asp:BoundField>
<asp:BoundField DataField="Employee" HeaderText="Employee" SortExpression="Employee">
</asp:BoundField>
<asp:BoundField DataField="mesec" HeaderText="Month" SortExpression="mesec">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="godina" HeaderText="Year" SortExpression="godina">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="CallDate" HeaderText="Call Date" SortExpression="CallDate">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="PhoneType" HeaderText="Phone Type" SortExpression="PhoneType">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="land" HeaderText="Land" SortExpression="land">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="number" HeaderText="Number" SortExpression="number">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Minutes" HeaderText="Minutes" SortExpression="Minutes">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Costs" HeaderText="Costs" SortExpression="Costs">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="privateCost" HeaderText="Private Costs" SortExpression="privateCost">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="Private" SortExpression="private" >
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("private") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("private") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Komentar" HeaderText="Commnet" SortExpression="Komentar">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>

Get link button text in gridview from delete button

I have a gridview with paging function.
the code below is my aspx code for gridview.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" GridLines="None" Width="768px" CellPadding="4" ForeColor="#333333" OnRowDeleting="OnRowDeleting" AllowPaging="True" PageSize="20" OnPageIndexChanging="gridView_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="SAP No" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click"
Text='<%#Eval("SAPNO") %>' runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PARTNO" HeaderText="Part No" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="10%">
</asp:BoundField>
<asp:BoundField DataField="PARTDESC" HeaderText="Description" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:BoundField DataField="MINQTY" HeaderText="Min Qty" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%">
</asp:BoundField>
<asp:BoundField DataField="QOH" HeaderText="QOH" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%">
</asp:BoundField>
<asp:BoundField DataField="CATEGORY" HeaderText="Category" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:BoundField DataField="EQUIPMENT" HeaderText="Equipment" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="20%">
</asp:BoundField>
<asp:CommandField ShowDeleteButton="true" ButtonType="Image" DeleteImageUrl="Image/delete.JPG" ControlStyle-Height="20px" ControlStyle-Width="50px" HeaderText="Delete">
<HeaderStyle Width="10%" HorizontalAlign="Left" /></asp:CommandField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
<PagerSettings Mode="NextPreviousFirstLast" FirstPageText="<--" PreviousPageText="<" NextPageText=">" LastPageText="-->" />
<PagerStyle HorizontalAlign="Center" BackColor="White" />
</asp:GridView>
At the back end code, i tried to retrieve the first column and specific rows but it throw me empty. the code below is how i retrieve.
int index = Convert.ToInt32(e.RowIndex);
string sapNo1 = GridView1.Rows[index].Cells[0].Text;
string partNo = GridView1.Rows[index].Cells[1].Text;
string partDesc = GridView1.Rows[index].Cells[3].Text;
I try to show all the value for sapNo1, it throw me blank but for partNo it will show the data in the gridview.
anyone has any idea about this?
I am really appreciate your help and comment!
As your first column is a linkbutton so retrieve that as it is then find the value.
string sapNo1 = GridView1.Rows[index].Cells[0].Text; // wrong code to retrieve data from linkbutton in a gridview
Modify this as :
LinkButton linkbtn =(LinkButton)GridView1.Rows[index].FindControl("LinkButton1");
string sapNo1 = linkbtn.Text;
or
string sapNo1 =(GridView1.Rows[index].FindControl("LinkButton1") as LinkButton).Text;
You can't get the controls properties present inside TemplateField like that, you need to find the control like this:-
LinkButton LinkButton1 = (LinkButton)GridView1.Rows[index].Cells[0]
.FindControl("LinkButton1");
After this you can simply fetch the properties of this control:-
string sapNo1 = LinkButton1.Text;
you can get the link button description by the below code
protected void Link_Button_Command(object sender, CommandEventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string name = button.ToString();
}
catch (Exception ex)
{
lbl_message.Text = ex.Message;
}
}

"Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index" in ASP.net

I want to display the "NDA ID" in a label When the user click on the select link in the grid view. But it gives the error as "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index".
Here is my code,
<asp:GridView ID="grdNDA" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="true" Font-Size="Small" Width="95%" onselectedindexchanged="grdNDA_SelectedIndexChanged" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="NDA ID" DataField="NDAid" DataFormatString="ISM/C/NDA/IT/{0}" />
<asp:BoundField HeaderText="Company Name" DataField="ComName" />
<asp:BoundField HeaderText="Country Incorperated" DataField="Country" />
<asp:BoundField HeaderText="Date Created" DataField="Date" />
</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>
<br>
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
Code behind
protected void grdNDA_SelectedIndexChanged(object sender, EventArgs e)
{
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[2].Text;
}
You should change this line
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[1].Text;
It worked using this
protected void form1_Load(object sender, EventArgs e)
{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add("NDAid");
dt.Columns.Add("ComName");
dt.Columns.Add("Country");
dt.Columns.Add("Date");
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[2] = "Country " + i;
dr[3] = DateTime.Now;
dt.Rows.Add(dr);
}
grdNDA.DataSource = dt;
grdNDA.DataBind();
}
protected void grdNDA_SelectedIndexChanged(object sender, EventArgs e)
{
lblValues.Text = "<b>ID:</b> " + grdNDA.SelectedRow.Cells[1].Text;
}
ASPX
<form id="form1" runat="server" onload="form1_Load">
<div>
<asp:GridView ID="grdNDA" runat="server" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateSelectButton="true" Font-Size="Small"
Width="95%" OnSelectedIndexChanged="grdNDA_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField HeaderText="NDA ID" DataField="NDAid" DataFormatString="ISM/C/NDA/IT/{0}" />
<asp:BoundField HeaderText="Company Name" DataField="ComName" />
<asp:BoundField HeaderText="Country Incorperated" DataField="Country" />
<asp:BoundField HeaderText="Date Created" DataField="Date" />
</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>
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
</div>
</form>

Categories