how to get DatakeyValue from gridview being populated with linq - c#

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;

Related

Display Names instead of Id in a GridView whose value is there in different table using asp.net

I have a gridView in which i have two foreign keys whose value is there in different table i am able to display only Id but i need to display its name based on its Id how to achieve it using asp.net
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#2A3F54" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" Width="100%" Height="100%" CellSpacing="30" CellPadding="50" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="order_id" HeaderText="ORDER ID" ItemStyle-Width="30" ItemStyle-Height="35" />
<asp:BoundField DataField="order_ref_no" HeaderText="ORDER REF NO" ItemStyle-Width="150" />
<asp:BoundField DataField="order_date" HeaderText="ORDER DATE" ItemStyle-Width="150" />
<asp:BoundField DataField="customer_id" HeaderText="CUSTOMER ID" ItemStyle-Width="150" />
<asp:BoundField DataField="first_name" HeaderText="USER NAME" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
my asp.net code
string customerText= customerDetails.SelectedItem.Value;
string queries = #"select * from app_order_master inner join app_user on app_user.user_id = app_order_master.user_id where app_order_master.user_id=" + customerText;;
using (DataTable dt = SMSDBHelperFE.ExecuteReaderDataTable(CommandType.Text, queries, null))
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Now i am only able to join one id value (user name) using inner join but i need to display customer name instead of ID How to achieve it using asp.net

PageIndex changes but data stays the same

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?

SelectDataKey in GridView

How do I grab the value from the SelectedDataKey function from the ButtonField? It keeps coming back null. Right now I've managed to create a foreach loop to actually see what value are available but this method is not ideal.
This is the ASP code
<asp:GridView ID="GridViewResults" AutoGenerateColumns="False" runat="server" HorizontalAlign="Center" CellPadding="10" CellSpacing="10" Width="1100px" SelectedRow="hotelId" GridLines="Horizontal" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" ForeColor="Black" DataKeyNames="hotelId" OnRowCommand="GridViewResults_RowCommand" >
<Columns>
<asp:ImageField DataImageUrlField="thumbNailUrl" DataImageUrlFormatString="https://media.expedia.com{0}" HeaderText="Image" />
<asp:BoundField DataField="name" HeaderText="Hotel Name" />
<asp:BoundField DataField="locationDescription" HeaderText="Location" />
<asp:BoundField DataField="hotelRating" DataFormatString="{0}/5" HeaderText="Hotel Rating" />
<asp:BoundField DataField="lowRate" DataFormatString="£{0}" HeaderText="Lowest Price" />
<asp:ButtonField Text="View" DataTextField="hotelId" HeaderText="View Hotel" ButtonType="Button" DataTextFormatString="{0}" />
<%-- <asp:HyperLinkField DataNavigateUrlFields="hotelId" HeaderText="View Hotel" DataNavigateUrlFormatString="http://api.ean.com/ean-services/rs/hotel/v3/info?apikey=5qjdrl3pjpj8f8gj6u7b40ofjk&sig=117f9d785e142c4be4285799ab8608b4&cid=488640&minorRev=99&customerUserAgent=Mozilla%2F5.0&customerIpAddress=84.246.168.11&locale=en_US&currencyCode=GBP&hotelId={0}" Text="View" />--%>
</Columns>
</asp:GridView>
This is the logic for the for each loop, but I want to grab the value which has been selected.
protected void GridViewResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
foreach (GridViewRow row in GridViewResults.Rows)
{
string _hotelId = GridViewResults.DataKeys[row.RowIndex].Value.ToString();
var searchListRequest = new RestRequest("/ean-services/rs/hotel/v3/info", Method.GET);
string hotelId = _hotelId;
}
}
Add CommandName="hotelId" in your ButtonField and inside your GridViewResults_RowCommand do the following.
protected void GridViewResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "hotelId")
{
int rowindex = Convert.ToInt32(e.CommandArgument);
int hotelId = Convert.ToInt32(GridViewResults.DataKeys[rowindex].Value);
}
}
Hope it helps.
Regards!

Delete row using gridview_rowdeleting event

I'm trying to delete a row in Grid View programmatically
I have created this GridView
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
and my code behind is:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this data?",
"Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mySqlString"].ConnectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM persons WHERE id = #id", conn);
MySqlParameter param = new MySqlParameter();
try
{
int rowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
cmd.Parameters.AddWithValue("#id", rowID);
conn.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
}
I'm getting the error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Your grid doesn't set the DataKeyNames property, so this grid isn't tracking any datakeys. Probably thats why you are getting an index error.
You should set the DataKeyNames property. In your code you also need to check to make sure the collection contains elements.The datakeys collection itself may not be null, but it can contain zero elements.
Use DataKeyNames="ID" like
<asp:GridView ID="GridView1" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display" DataKeyNames="ID"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>
Then it will work for you
Your forgot to add DataKeyNames to your gridview
DataKeyNames="Valid Column Name" //Column name here instead of Valid Column name
Full Code below :
<asp:GridView ID="GridView1" DataKeyNames="Valid Column Name" CssClass="HeaderTables" runat="server" AllowPaging="True"
EmptyDataText="There is no data record to display"
AllowSorting="True" AutoGenerateColumns="false"
CellPadding="0" Height="0px" Width="800px"
onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="first_name" HeaderText="First name"/>
<asp:BoundField DataField="last_name" HeaderText="Last name"/>
<asp:BoundField DataField="mobile_phone" HeaderText="Mobile number"/>
<asp:BoundField DataField="email" HeaderText="Email"/>
<asp:BoundField DataField="city" HeaderText="City"/>
<asp:BoundField DataField="street_number" HeaderText="Street number"/>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
<HeaderStyle HorizontalAlign="Left" />
<RowStyle HorizontalAlign="Left" />
</asp:GridView>

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" />

Categories