PageIndex changes but data stays the same - c#

I have a GridView that I bind a list to from data retrieved via edmx. My issue is when I click on pagers, the page changes, and I have debugged and know that it's changing the value, but it always just shows the data from the first page. What am I missing? Oh, and I call LoadAllRequestsData() from Page_Load in an if(!Page.IsPostBack).
<cm:GridControl runat="server" ID="gvAllRequests" DataKeyNames="Number" OnPageIndexChanging="AllRequestsGridViewPageIndexChanging" ShowHeaderWhenEmpty="True" EmptyDataText="No requests to show." >
<Columns>
<asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number" InsertVisible="False" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" SortExpression="CustomerId" Visible="False"></asp:BoundField>
<asp:BoundField DataField="Customer" HeaderText="Customer" SortExpression="Customer" Visible="False"></asp:BoundField>
<asp:BoundField DataField="TypeId" HeaderText="TypeId" SortExpression="TypeId" Visible="False"/>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type"></asp:BoundField>
<asp:BoundField DataField="Note" HeaderText="Note" SortExpression="Note"/>
<asp:BoundField DataField="RequestedOn" HeaderText="Requested On" SortExpression="RequestedOn"/>
<asp:BoundField DataField="RequestedById" HeaderText="RequestedById" SortExpression="RequestedById" Visible="False" />
<asp:BoundField DataField="RequestedBy" HeaderText="Requested By" SortExpression="RequestedBy" />
<asp:BoundField DataField="CompletedOn" HeaderText="Completed On" SortExpression="CompletedOn" />
<asp:BoundField DataField="CompletedById" HeaderText="CompletedById" SortExpression="CompletedById" Visible="False"/>
<asp:BoundField DataField="CompletedBy" HeaderText="Completed By" SortExpression="CompletedBy" />
<asp:BoundField DataField="LastModifiedOn" HeaderText="LastModified On" SortExpression="LastModifiedOn" />
<asp:BoundField DataField="LastModifiedById" HeaderText="LastModifiedById" SortExpression="LastModifiedById" Visible="False"/>
<asp:BoundField DataField="LastModifiedBy" HeaderText="LastModified By" SortExpression="LastModifiedBy" />
<asp:CheckBoxField DataField="IsDeleted" HeaderText="IsDeleted" SortExpression="IsDeleted" Visible="False"/>
</Columns>
</cm:GridControl>
private void LoadAllRequestsData(string sortExpression = "RequestedOn", SortDirection sortDirection = SortDirection.Descending)
{
var db = new CrewManagerEntities();
var list = db.GetAllRequestsByUserId(_customerId).ToList();
if (!string.IsNullOrEmpty(sortExpression))
{
list = list.AsQueryable().OrderBy(sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC")).ToList();
gvAllRequests.SetSort(sortExpression, sortDirection);
}
gvAllRequests.DataSource = list;
gvAllRequests.DataBind();
}
protected void AllRequestsGridViewPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvAllRequests.PageIndex = e.NewPageIndex;
LoadAllRequestsData();
}
Edit: So, I tried using SqlDataSource instead of doing call in codebehind and using a list and the paging works. That is fine but I would like to know why the list doesn't work as there may be instances where I need to use a list source. Any ideas?

Related

Gridview controllers null after inserting column

I am developing a Web App for managing Student exam entries but I am coming across an issue with my gridview.
The basic idea is that a user can go on and enter and update details on a students exam. Complications arise when certain subjects require different fields to be populated and this is where my issue is.
The exception is thrown when the Save Button method is run. I get a Null Object reference thrown when running the AddAudit and UpdateRecord methods. After some debugging from the looks of it the issue is the controls (ddlDate, txtAssesmentLevel etc) are not being declared from the FindCotrol method of the gridview meaning when the AddAudit and UpdateRecord methods are called they point to a null controller.
Be aware that this issue does not occur when the code is not "C2555" which leads me to suspect the issue is with dynamically adding columns and controls getting muddled up though i am not sure.
Any assistance would be great and feel free to ask for more information.
Below is my basic code:
Page Load Method
protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack){
//Selected class passed through
selectedClass sc = (selectedClass)Session["selectedClass"] as selectedClass;
//Get Class Code
lblAosCode.Text = sc.getAOSCode();
//If class is English
if(lblAosCode.Text == "C2555"){
TemplateField speakingListening = new TemplateField();
speakingListening.HeaderText = "Speaking and Listening";
dgvSelectedClasses.Columns.Insert(7, speakingListening);
}
//Populate Gridview
DataTable dsSelectedClasses = AccessData.getSelectedClasses(sc.getAOSCode(), sc.getAOSPeriod(), sc.getDescription());
dgvSelectedClasses.DataSource = dsSelectedClasses;
dgvSelectedClasses.DataBind();
//Check if txtAssesmentLevel is populated
for (int index = 0; index < dgvSelectedClasses.Rows.Count; index++)
{
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[index].FindControl("txtAssessmentLevel");
if (dgvBefore.Rows[index].Cells[4].Text != " ")
{
txtAssessmentLevel.ReadOnly = true;
}
}
}
}
Save Method (Exception Thrown)
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvSelectedClasses.Rows.Count; i++)
{
DropDownList ddlL1L2 = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlL1L2");
DropDownList ddlExamDate = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlExamDate");
TextBox txtAssessmentLevel = (TextBox)dgvSelectedClasses.Rows[i].FindControl("txtAssessmentLevel");
DropDownList ddlSpeakingListening = null;
if (lblAosCode.Text.Contains("C2555"))
{
ddlSpeakingListening = (DropDownList)dgvSelectedClasses.Rows[i].FindControl("ddlSpeakingListening");
}
if (IsPostBack)
{
if (lblAosCode.Text.Contains("C2555"))
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[15].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Speaking and Listening", ddlSpeakingListening.SelectedValue, dgvBefore.Rows[i].Cells[7].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text, ddlSpeakingListening.SelectedValue);
}
else
{
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Assessment Level", txtAssessmentLevel.Text, dgvBefore.Rows[i].Cells[4].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam request L1 or L2", ddlL1L2.SelectedValue, dgvBefore.Rows[i].Cells[13].Text);
AccessData.addAudit(dgvSelectedClasses.Rows[i].Cells[0].Text, Context.User.Identity.Name, "Exam Date", ddlExamDate.SelectedValue, dgvBefore.Rows[i].Cells[14].Text);
AccessData.updateRecord(txtAssessmentLevel.Text, ddlL1L2.SelectedValue, ddlExamDate.SelectedValue, lblAosCode.Text, lblAosPeriod.Text, dgvSelectedClasses.Rows[i].Cells[0].Text);
}
}
}
Response.Redirect("~/contact");
}
On Row Data Bound
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (lblAosCode.Text.Contains("C2555"))
{
DropDownList ddlSpeakingListening = new DropDownList();
ddlSpeakingListening.ID = "ddlSpeakingListening";
ddlSpeakingListening.Items.Add("L1");
ddlSpeakingListening.Items.Add("L2");
ddlSpeakingListening.Items.Add("Entry");
ddlSpeakingListening.Items.Add("NS");
e.Row.Cells[7].Controls.Add(ddlSpeakingListening);
}
}
}
ASP.NET
<asp:GridView ID="dgvSelectedClasses" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:TemplateField HeaderText="Assessment Level">
<ItemTemplate>
<asp:TextBox ID="txtAssessmentLevel" Text ='<%#Bind("AssessmetLevel") %>' runat="server" Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="Achievelevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Last Update" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:TemplateField HeaderText="Exam request L1 or L2" >
<ItemTemplate>
<asp:DropDownList ID="ddlL1L2" runat="server" >
<asp:ListItem>Not Set</asp:ListItem>
<asp:ListItem>L1</asp:ListItem>
<asp:ListItem>L2</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam date">
<ItemTemplate>
<asp:DropDownList ID="ddlExamDate" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="dgvBefore" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" />
<asp:BoundField DataField="StageCode" HeaderText="Stage Code" ReadOnly="True" />
<asp:BoundField DataField="Forename" HeaderText="Forename" ReadOnly="True" />
<asp:BoundField HeaderText="Surname" DataField="Surname" />
<asp:BoundField DataField="AssessmetLevel" HeaderText="Assessment Level" NullDisplayText=" "/>
<asp:BoundField DataField="TargetLevel" HeaderText="Target Level" />
<asp:BoundField DataField="AchieveLevel" HeaderText="Achieve Level" />
<asp:BoundField DataField="FELSOutcome" HeaderText="FELS Outcome" />
<asp:BoundField DataField="Registration" HeaderText="Registration" />
<asp:BoundField DataField="DateSpreadsheetSent" HeaderText="Date Spreadsheet Sent" />
<asp:BoundField DataField="Dayofclass" HeaderText="Day of class" />
<asp:BoundField DataField="Timeofclass" HeaderText="Time of class" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="ExamrequestL1orL2" HeaderText="Exam request L1 or L2" />
<asp:BoundField DataField="Examdate" HeaderText="Exam date" />
<asp:BoundField DataField="Reviewed" HeaderText="Reviewed" />
</Columns>
</asp:GridView>
P.S. This is my first question hopefully it makes sense and I am open to pointers :)
Edit: The page load method does include code to populate dgvBefore as well as a few authentications thing i just forgot to include it.
I think you need to add the drop down list column on every postback. Refer this link : https://www.codeproject.com/Tips/682689/Add-populated-dropdownlist-to-GridView-dynamically

multiple select buttons in gridview

I'm trying to create multiple select buttons in grid view
however I seem to be having some issues
the record is not selected using the code below
<asp:GridView ID="GridView1" runat="server" CssClass="table table-bordered text-nowrap" AutoGenerateColumns="False" DataKeyNames="Qutation_ID" OnRowDeleting="GridView1_RowDeleting" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Qutation_ID" HeaderText="Qutation ID" InsertVisible="False" ReadOnly="True" SortExpression="Qutation_ID" />
<asp:BoundField DataField="CustID" HeaderStyle-CssClass="hiddencol" HeaderText="Customer ID" InsertVisible="False" ItemStyle-CssClass="hiddencol" ReadOnly="True" SortExpression="Qutation_ID">
<HeaderStyle CssClass="hiddencol" />
<ItemStyle CssClass="hiddencol" />
</asp:BoundField>
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Subject" HeaderText="Subject" SortExpression="Subject" />
<asp:ButtonField Text="Click" CommandName="ActionCommand" ItemStyle-Width="30" />
</Columns>
<EmptyDataTemplate>
"No records found"
</EmptyDataTemplate>
</asp:GridView>
protected void ActionCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ActionCommand")
{
msg.Text = GridView1.SelectedRow.Cells[1].Text;
}
}

Gridview: Index was out of range. Must be non-negative and less

I want to get the value from my gridview depending on the row I select.
I am getting the error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string name = GridView1.SelectedRow.Cells[0].Text;
}
/*---------------------------------------------------------------------------*/
<asp:GridView ID="GridView1"
OnSelectedIndexChanged = "OnSelectedIndexChanged"
autogeneratecolumns="false" runat="server">
<Columns>
<asp:BoundField DataField="ESS_ID" HeaderText="ID" Visible=false/>
<asp:BoundField DataField="ESS_Pay_Dt" HeaderText="Pay Date" DataFormatString="{0:d}"
HtmlEncode="false" ItemStyle-Width="100" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Name" HeaderText="Employee Name" ItemStyle-Width="250" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Num" HeaderText="Number" ItemStyle-Width="75" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Emp_Dept" HeaderText="Department" ItemStyle-Width="100" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Pay_End_Dt" HeaderText="Pay End Date" Visible="false" />
<asp:BoundField DataField="ESS_Net_Amt" HeaderText="Net Amount" ItemStyle-Width="150" HeaderStyle-BorderColor=navy ItemStyle-BorderColor="navy" ItemStyle-HorizontalAlign="center"/>
<asp:BoundField DataField="ESS_Total_Earnings1" HeaderText="Total Earnings1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Earnings2" HeaderText="Total Earnings2" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Taxes1" HeaderText="Total Taxes1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Taxes2" HeaderText="Total Taxes2" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Deductions1" HeaderText="Total Deductions1" Visible="false"/>
<asp:BoundField DataField="ESS_Total_Deductions2" HeaderText="Total Deductions2" Visible="false"/>
<asp:BoundField DataField="ESS_Net_Pay1" HeaderText="Net Pay1" Visible="false"/>
<asp:BoundField DataField="ESS_Net_Pay2" HeaderText="Net Pay2" Visible="false"/>
<asp:BoundField DataField="ESS_Vac_Hrs" HeaderText="Vacation Hours" Visible="false"/>
<asp:BoundField DataField="ESS_Sck_Hrs" HeaderText="Sick Hours" Visible="false" />
<asp:BoundField DataField="ESS_Batch_Num" HeaderText="Batch Number" Visible="false"/>
<asp:BoundField DataField="ESS_Load_Count" HeaderText="Load Count" Visible="false"/>
<asp:BoundField DataField="ESS_Load_Dt" HeaderText="Load Date" Visible="false"/>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
you appear to be in the wrong EventHandler try the following example
private void GridView1_SelectionChanged(object sender, EventArgs e)
{
if (GridView1.SelectedCells.Count > 0)
{
int selectedrowindex = GridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = GridView1.Rows[selectedrowindex];
name = Convert.ToString(selectedRow.Cells["Cell Zero's Name goes here"].Value);
}
}
if you are going to use the name local variable outside of this method then string name needs
to be declared outside the local scope
for example at the class level declare it as the following then you can use it globally
public static string name = string.Empty;
Some additional Methods / Events you can checkout as well DataGrid.SelectedItem Property

How to show empty data row in gridview control

Here I am working with gridview here is the gidview binding
conn = new SqlConnection(strconnection);
string squery = "sql query";
da = new SqlDataAdapter(squery, conn);
ds = new DataSet();
da.Fill(ds, "tbl1");
GridView1.DataSource = ds;
GridView1.DataBind();
This the gridview control asp code
<asp:GridView ID="GridView1" runat="server" GridLines="None"
HeaderStyle-CssClass="grid_header"
RowStyle-CssClass="grid_item"
RowStyle-Height="30px"
AutoGenerateColumns="false" Width="775px" EmptyDataText="Empty">
<Columns>
<asp:BoundField HeaderText="Order Code" DataField="ordercode"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" />
<asp:BoundField HeaderText="Transation Code" DataField="transcode"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Name" DataField="product"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Started" DataField="Start_d"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Plan Ending" DataField="End_d"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:CheckBoxField HeaderText="Payed" DataField="Payed"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Pay Date" DataField="PayDate"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Payed Amt" DataField="amtpaid"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Pay Amt" DataField="PayAmount"
HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
This is result emp like this
Header1 header2 header3 header4
1 asdas 22sdas asdasda
2 sasa asdasas
3 asdas
4 asdasas
like this result
Here my problem is I want show the NULL places just show the "EMPTY" Message. How can I do that?
You can use NullDisplayText="EMPTY" NullDisplayText Attribute
<asp:BoundField DataField="transcode"
NullDisplayText="EMPTY"
HeaderText="header2"/>
If what is coming from your DB is not NULL but an empty string, you will need to use template field
<asp:TemplateField HeaderText="header2">
<ItemTemplate>
<%# Eval("transcode").ToString() == "" ? "EMPTY" : Eval("transcode").ToString() %>
</ItemTemplate>
</asp:TemplateField>
Check out BoundField.NullDisplayText
Gets or sets the caption displayed for a field when the field's value
is null.
Sometimes a field's value is stored as null in the data source. You can specify a custom caption to display for fields that have a null value by setting the NullDisplayText property.
In your case, you can use it like;
<asp:BoundField NullDisplayText="EMPTY" HeaderText="Order Code" DataField="ordercode" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
Since you didn't write your sql query, as an alternative, you can use ISNULL functions for your columns.
Replaces NULL with the specified replacement value.
For example;
SELECT ISNULL(Column1, "EMPTY")
Since you asked, How to change null text color? You can use RowDataBound event for this process. For example;
<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">
</asp:GridView>
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Use for loop for based all rows.
if(e.Row.Cells[i].Text == "EMPTY")
e.Row.Cells[i].BackColor = Color.Red;
}
}
You just need to add :
NullDisplayText="Empty"
Like:
<asp:BoundField HeaderText="Order Code" DataField="ordercode" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" NullDisplayText="Empty" />

how to get DatakeyValue from gridview being populated with linq

I have the following gridview:
<asp:GridView ID="gvNOVs" runat="server" AllowPaging="true" AllowSorting="true" PageSize="10"
AutoGenerateColumns="false" Width="100%" BackColor="Transparent" GridLines="None"
RowStyle-HorizontalAlign="Left" PagerSettings-Mode="NumericFirstLast" DataKeyNames="NOVID"
OnRowDataBound="gvNOVs_RowDataBound"
OnRowCommand="gvNOVs_OnSelectRow"
OnPageIndexChanging="gvNOVs_PageIndexChanging"
OnSorting="gvNOVs_OnSorting"
>
<AlternatingRowStyle CssClass="alternateItemStyle" />
<HeaderStyle CssClass="headerStyle" />
<PagerSettings Mode="NumericFirstLast" />
<RowStyle CssClass="itemStyle" />
<Columns>
<asp:BoundField DataField="NOVID" HeaderText="NOVID" InsertVisible="false" ReadOnly="true" Visible="false"/>
<asp:BoundField DataField="NOVNumber" HeaderText="NOV Number" SortExpression="NOVNumber"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="NOVDate" HeaderText="NOV Date" SortExpression="NOVDate"
ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" />
<asp:BoundField DataField="CompanyName" HeaderText="Company Name" SortExpression="CompanyName"
ItemStyle-HorizontalAlign="Center"></asp:BoundField>
<asp:BoundField DataField="CargoTankID" HeaderText="Cargo Tank Number" SortExpression="CargoTankNumber"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="ARBInspectorFirstName" HeaderText="InspectorFirstName"
SortExpression="InspectorFirstName" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="ARBInspectorLastName" HeaderText="InspectorLastName" SortExpression="InspectorLastName"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="ViolationName" HeaderText="Violation Name" SortExpression="ViolationName"
ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
It is being populated on the page load event using linq:
var NOVs = from n in db.CT_NOVs
join i in db.CT_Inspectors on n.ARBInspectorID equals i.CTInspectorID
join v in db.CT_ViolationTypes on n.ViolationTypeID equals v.ViolationTypeID
join t in db.CT_Tanks on n.CargoTankID equals t.CargoTankID
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
orderby n.NOVNumber descending
select new
{
n.NOVID,
n.NOVNumber,
NOVDate = n.NOVDate.Value.ToShortDateString(),
ARBInspectorFirstName = i.FirstName,
ARBInspectorLastName = i.LastName,
v.ViolationName,
t.CargoTankID,
c.CompanyName
};
this.gvNOVs.DataSource = NOVs;
this.gvNOVs.DataBind();
When I click on a row, I call this method:
protected void gvNOVs_OnSelectRow(object sender, GridViewCommandEventArgs e)
{
}
I'm not sure how to get the datakeyValue, I want to get the NOVID for the row that was clicked on. If I get e.CommandArgument.ToString(), it gives me the value for CargoTankID, I have no idea why it gives me that value.
Anybody know how to get the NOVID for the row selected?
This might work.
Get the index from the CommandArgument
Get the grid itself from the CommandSource
Get the data source
Get the data item at the index
int index = int.Parse((string)e.CommandArgument);
var grid = (GridView)e.CommandSource;
var data = (IList)grid.DataSource;
var NOVID = data[index].NOVID;
you should try something like this
string dataKeyValue = (string)this.gvNOVs.SelectedDataKey.Value;

Categories