How can I find a BoundField inside a GridView by DataField? - c#

I want to change the CSS class behind the tenth BoundField inside my GridView, but I'd like to find it by DataField (i.e., use a string as index).
protected void gdDeliveryDates_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string DeliveryDue = DataBinder.Eval(e.Row.DataItem, "DeliveryDue").ToString();
((LinkButton) e.Row.FindControl("PostDelivery")).Enabled = !String.IsNullOrEmpty(DeliveryDue);
//e.Row.Cells[9].CssClass= "badge";
}
}
In the code above I have commented out the only solution I've found so far, which to me is unacceptable because a column number (i.e., column 9 as specified above) is very volatile. I would prefer to find the column by DataField (a string, in this case, "MailCount" as you'll see in the grid declaration further ahead). Below is what my grid looks like:
<asp:GridView ID="gdDeliveryDates" runat="server" AllowPaging="False" AllowSorting="True" DataSourceID="odsDeliveryDates" AutoGenerateColumns="False" CssClass="table table-striped table-bordered table-hover" OnRowCommand="gdDeliveryDates_RowCommand" OnSelectedIndexChanged="gdDeliveryDates_SelectedIndexChanged" DataKeyNames="PackageOfferedID, PackageID, PostageID, PackageNumber, PackageTitle, PostageName, Section, PostageStart, PostageEnd, DeliveryDue, LName, MailCount, Location" OnRowDataBound="gdDeliveryDates_RowDataBound" >
<Columns>
<asp:BoundField DataField="PackageID" HeaderText="PackageID" Visible="False" ReadOnly="True" SortExpression="PackageID" />
<asp:BoundField DataField="PackageOfferedID" HeaderText="PackageOfferedID" Visible="False" ReadOnly="True" SortExpression="PackageOfferedID" />
<asp:BoundField DataField="PostageID" HeaderText="PostageID" Visible="False" ReadOnly="True" SortExpression="PostageID" />
<asp:BoundField DataField="PackageNumber" HeaderText="Package" Visible="True" ReadOnly="True" SortExpression="PackageNumber" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageName" HeaderText="Postage" ReadOnly="True" SortExpression="PostageName" HeaderStyle-CssClass="visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-sm visible-md visible-lg"/>
<asp:BoundField DataField="Section" HeaderText="Section" ReadOnly="True" SortExpression="Section" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageStartDate" HeaderText="Start Date" ReadOnly="True" SortExpression="PostageStartDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="PostageEndDate" HeaderText="End Date" ReadOnly="True" SortExpression="PostageEndDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="DeliveryDueDate" HeaderText="Delivery Due" ReadOnly="True" SortExpression="DeliveryDueDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="MailCount" HeaderText="#" Visible="True" ReadOnly="True" SortExpression="MailCount" HeaderStyle-CssClass="visible-lg" ItemStyle-CssClass="visible-lg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="PostDelivery" runat="server" CausesValidation="false" CommandName="Add"
Text="Post Delivery" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CssClass="buttonLayout" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LName" HeaderText="LName" Visible="False" ReadOnly="True" SortExpression="LName" />
<asp:BoundField DataField="Location" HeaderText="Location" Visible="False" ReadOnly="True" SortExpression="Location" />
</Columns>
</asp:GridView>

This is not possible but you can try this method:
public int FindIndexByDataField(this GridView gv, string datafieldname)
{
int index = -1, cnum = 0;
foreach (DataControlField col in gv.Columns)
{
if (col is BoundField)
{
BoundField coll = (BoundField)gv.Columns[cnum];
if (coll.DataField == datafieldname)
{
index = cnum;
break;
}
}
cnum++;
}
return index;
}
And call above method like this:
e.Row.Cells[FindIndexByDataField("MailCount")].CssClass= "badge";

Related

selectedrow on hidden boundfield

I've done my research here and I can now succesfully get a value of a hidden boundfield column in my gridview. The problem is I can't target the a hidden column of the row that I selected.
can I use GridView1.SelectedRow.Cells[7].Text; something like that on a hidden column.Is it possible?
here is my code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//GridView1.Columns[7].Visible = true;
//stock_id_gridview_1();
foreach (GridViewRow row in GridView1.Rows)
{
string id = GridView1.DataKeys[row.RowIndex]["id"].ToString();
con.Open();
cmd = new SqlCommand(#"SELECT transaction_id,transaction_number
FROM stocks_history
WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", id);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
transaction_id = rdr["transaction_id"].ToString();
//lbl_test_id.Text = rdr["transaction_id"].ToString();
transaction_number = rdr["transaction_number"].ToString();
lbl_test_id.Text = transaction_id + " " + transaction_number;
}
}
con.Close();
}
here is my gridview:
<asp:GridView ID="GridView1"
CssClass="table table-hover table-striped"
runat="server"
AutoGenerateColumns="False" DataKeyNames="id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="productName" HeaderText="Product Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_name" HeaderText="Stock Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_id" HeaderText="Stock I.D."
SortExpression="DateField" />
<asp:BoundField DataField="stock_in" HeaderText="Stock In"
SortExpression="DateField" />
<asp:BoundField DataField="stock_out" HeaderText="Stock Out"
SortExpression="DateField" />
<asp:BoundField DataField="stock_on_hand" HeaderText="On hand"
SortExpression="DateField" />
<asp:BoundField DataField="max_date" HeaderText="Date & Time"
DataFormatString="{0:MM-dd-yyyy hh:mm tt}"
SortExpression="DateField" />
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" ControlStyle-CssClass="btn btn-info btn-sm" CommandName="Select" ItemStyle-Width="150" HeaderText="Review">
<ControlStyle CssClass="btn btn-info btn-sm"></ControlStyle>
<ItemStyle Width="150px"></ItemStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
I wanted to target this bound field:
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
If You use attribute DataKeyNames, you can take value from invisible column like
Use Attribute
<asp:GridView runat="server" ID="GridView" DataKeyNames="id">
</asp:GridView>
And you can access the data
var id = GridView.DataKeys[RowIndex].Values[KeyIndex]
To get selected row hidden column value
var id = GridView.DataKeys[GridView.SelectedRow.RowIndex].Values[0];

Not able to access hyperlink column inside gridview from code behind

I want to access the HyperLinkField column of the GridView from code behind but I am unable to do so.
I have the column in my dataset but I am still not able to use it.
My HyperLinkField column is named Status.
Here is what I tried:
UltraWebGrid1.DataSource = ObjPriDsGrid;
UltraWebGrid1.DataBind();
string StrPriStatus = "";
for (int IntPriI = 0; IntPriI < UltraWebGrid1.Rows.Count; IntPriI++)
{
if (UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim() != null)
{
StrPriStatus = UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim();
}
else
{
}
if (StrPriStatus == "5")
{
UltraWebGrid1.Rows[IntPriI].Cells[8].Text = ""; // Not getting status column here
}
}
Here is my GridView:
<asp:GridView ID="UltraWebGrid1" ShowHeader="true" runat="server" AutoGenerateColumns="false"
DataKeyNames="mkey" OnRowDataBound="Grid_RowDataBound" Width="98%" Height="30%"
PageSize="10" AllowPaging="true" OnPageIndexChanging="Grid1_PageIndexChanging"
ShowFooter="true" CssClass="Grid">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlGrid" runat="server" Style="display: none">
<asp:GridView ID="Grid2" runat="server" AutoGenerateColumns="false" Width="600px"
CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="80px" DataField="RefMkey" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="150px" DataField="CurrentUser" HeaderText="Current User" />
<asp:BoundField ItemStyle-Width="180px" DataField="Department" HeaderText="Current Department" />
<asp:BoundField ItemStyle-Width="100px" DataField="remarks" HeaderText="Remarks" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="0px" DataField="mkey" Visible="false" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="8%" DataField="Doc_No" HeaderText="IW/ No" />
<asp:BoundField ItemStyle-Width="10%" DataField="Doc_Date" HeaderText="IW/ Date" />
<asp:BoundField ItemStyle-Width="12%" DataField="DocType" HeaderText="Doc type" />
<asp:BoundField ItemStyle-Width="15%" DataField="Party_Name" HeaderText="Party Name" />
<asp:BoundField ItemStyle-Width="0" Visible="true" DataField="Status_Flag" HeaderText="Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="LastAction_datetime" HeaderText="Last Action Date" />
<asp:BoundField ItemStyle-Width="10%" DataField="CurrStatus" HeaderText="Current Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="Type_desc" HeaderText="Resp Dept" />
<asp:BoundField ItemStyle-Width="12%" DataField="UserName" HeaderText="Resp User" />
<asp:BoundField ItemStyle-Width="8%" DataField="No_Of_Days" HeaderText="No of days" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/FrmInwardNextAction.aspx?Inward_mkey={0}&Status={0}&IWNO={0}"
HeaderText="Status" DataTextField="Status" Target="_blank" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
HeaderText="View" DataTextField="View" Target="_blank" DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/InwardDocDetails.aspx?Key={0}&Status={0}&IWNO={0}" />
</Columns>
</asp:GridView>
Columns like HyperLinkField and CheckBoxField behave a little differently than BoundField. They don't just simply contain text like BoundField. You have to get the control within the cell. You can get the child controls of the cell using the Controls collection. We know that specifically for a HyperLinkField, the HyperLink will be the first control in the collection.
HyperLink hyp = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
Can you try it like this
if (StrPriStatus == "5")
{
HyperLink HyperLinkObj = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
HyperLinkObj.Text = "";
}

The wait operation timed out - Lengthen Timeout Period

I have a grid view that is populated on a button click event:
<asp:GridView CssClass="hoursGrid" ID="hoursReportGridView" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" DataSourceID="SqlDataSource2" OnRowDataBound="hoursReportGridView_OnRowDataBound" DataKeyNames="DifferentUsers, DoubleBookedFlag, PointPerson, Person">
<Columns>
<asp:BoundField DataField="Person" HeaderText="Person" SortExpression="Project" />
<asp:BoundField DataField="Project" HeaderText="Project" SortExpression="Project" />
<asp:BoundField DataField="ProjectType" HeaderText="Project Type" ReadOnly="True" SortExpression="Sprint" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Theme" HeaderText="Theme" ReadOnly="True" SortExpression="Theme" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="StoryNumber" HeaderText="Story Number" SortExpression="Story" ItemStyle-Width="6%" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="StoryTitle" HeaderText="Story Title" SortExpression="Story" ItemStyle-Width="20%" />
<asp:BoundField DataField="Effort" HeaderText="Effort" SortExpression="Effort" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Task" HeaderText="Task" SortExpression="Task" ItemStyle-Width="20%" HtmlEncode="false" />
<asp:BoundField DataField="OriginalEstimateHours" HeaderText="Original Estimate" SortExpression="OriginalEstimateHours" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Monday" HeaderText="Mon" ReadOnly="True" SortExpression="Monday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Tuesday" HeaderText="Tues" ReadOnly="True" SortExpression="Tuesday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Wednesday" HeaderText="Wed" ReadOnly="True" SortExpression="Wednesday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Thursday" HeaderText="Thurs" ReadOnly="True" SortExpression="Thursday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Friday" HeaderText="Fri" ReadOnly="True" SortExpression="Friday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Saturday" HeaderText="Sat" ReadOnly="True" SortExpression="Saturday" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField DataField="Sunday" HeaderText="Sun" ReadOnly="True" SortExpression="Sunday" ItemStyle-HorizontalAlign="Right" />
<asp:TemplateField HeaderText="Total" ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:LinkButton ID="taskLinkButton" Text='<%# Eval("Total") %>' Enabled='<%# Eval("StoryTitle").ToString() != "" %>' runat="server" OnClick="taskLinkButton_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#:
private void generateReport()
{
//set sql parameters
SqlDataSource2.SelectParameters["userParam"].DefaultValue = currentEntity;
SqlDataSource2.SelectParameters["startDateParam"].DefaultValue = startingDay.ToString();
SqlDataSource2.SelectParameters["endDateParam"].DefaultValue = endingDay.ToString();
SqlDataSource2.SelectParameters["orgTeamPK"].DefaultValue = orgTeam;
SqlDataSource2.SelectParameters["productId"].DefaultValue = productId;
SqlDataSource2.SelectParameters["theme"].DefaultValue = themeSelected;
hoursReportGridView.DataBind();
}
The query can take up to 45 seconds in SSMS and is resulting in the website crashing:
The wait operation timed out
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.ComponentModel.Win32Exception: The wait
operation timed out
Until a more efficient query can be created, is it possible to make the timeout period longer so that the program wont crash?
You could increase the CommandTimeout property. Add the OnSelecting event handler of your SqlDataSource, and in your code behind add the following:
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.CommandTimeout = 60;
}

Value from row with DropDownList on DropDownList Index Changed Event

Code:
<asp:GridView ID="gv_Recruit" AutoGenerateColumns="False" Width="100%"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlCities" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl_selected">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Recruiter" DataField="Recruiter" />
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
Code Behind:
protected void ddl_selected(object sender, EventArgs e)
{
string _dd_value = ((DropDownList)sender).SelectedValue;
string trying_to_get = gv_Recruit.Rows[???].Cells[0].Text.ToString();
string also_tried = gv_Recruit.SelectedRow.Cells[0].Text.ToString();
}
Basically what I'm trying to do is get the key value from the first row when the drop down is changed so I can perform an update ???
Can't figure this out.
Thanks in advance for the help...
Try
GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;
string trying_to_get = string.Empty;
if (gRow != null)
{
trying_to_get = gRow.Cells[0].Text;
}

asp.net Gridview: buttons accessing data for each row

I'm trying to code a Gridview that has a button on each row that when clicked will expose that particular rows data for use, but I'm not sure how the data would be passed.
The Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="ID" Visible="False" />
<asp:BoundField DataField="RelationID" HeaderText="RelationID" InsertVisible="False"
SortExpression="RelationID" Visible="False" />
<asp:BoundField DataField="UserRole" HeaderText="UserRole" InsertVisible="False"
SortExpression="UserRole" Visible="False" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" SortExpression="Telephone" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="Hash" HeaderText="Hash" InsertVisible="False" SortExpression="Hash"
Visible="False" />
<asp:BoundField DataField="DateCreated" HeaderText="Date Invited" SortExpression="DateCreated" />
<asp:TemplateField HeaderText="Resend Welcome Email">
<ItemTemplate>
<asp:Button runat="server" ID="btnResend" Text="Resend" OnClick="btnResend_Click" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The button_OnClick
protected void btnResend_Click(object sender, EventArgs e)
{
bool boolEmailSent = Email.sendWelcomeEmail(//Email from Row, //FirstName from Row, //Surname from Row, //Hash from Row);
if (boolEmailSent == true)
{
//Confirm to User
}
else
{
//TODO: write error to log
}
}
This article covers what you're attempting in more depth than we could answer here:
http://authors.aspalliance.com/aspxtreme/webforms/controls/addingbuttonfieldstoGridView.aspx
And here's another:
http://msdn.microsoft.com/en-us/library/bb907626.aspx

Categories

Resources