Gridview grouping - using gridviewheper - c#

Good night,
I used the gridviewhelper to group the rows in a gridview.
GridViewHelper helper = new GridViewHelper(this.Resultados);
helper.RegisterGroup("EntidadeNome", true, true);
helper.GroupHeader += new GroupEvent(helper_GroupHeader);
this.Resultados.DataSource = DT;
this.Resultados.DataBind();
Each row as two itemtemplate, each one with a checkbox.
<asp:GridView ID="Resultados" runat="server" AutoGenerateColumns="false" GridLines="None"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
ShowHeader="false">
<Columns>
<asp:BoundField DataField="EntidadeNome" SortExpression="EntidadeNome" />
<asp:BoundField DataField="ID" HeaderText="IDLinhascompras" ItemStyle-CssClass="hidden"
HeaderStyle-CssClass="hidden" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Artigo" HeaderText="Artigo" SortExpression="Artigo" ItemStyle-Width="50px"
ItemStyle-HorizontalAlign="Center" />
// Some BoundFieds here
<asp:TemplateField HeaderText="A" ItemStyle-Width="40px" SortExpression="A">
<ItemTemplate>
<asp:CheckBox ID="A" Width="40" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="R" ItemStyle-Width="40px" SortExpression="R">
<ItemTemplate>
<asp:CheckBox ID="R" Width="40" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<label>Sem resultados para apresentar</label>
</EmptyDataTemplate>
</asp:GridView>
I'm having some problems when i search for the rows that have a checkbox checked.
protected void EnviaArtigos_Click(object sender, EventArgs e)
{
CheckBox chkA, chkR;
foreach (GridViewRow dataItem in Resultados.Rows)
{
object rows;
chkA = (CheckBox)dataItem.FindControl("A");
chkR = (CheckBox)dataItem.FindControl("R");
if (chkA.Checked)
{
try
{
Motor.DSO.BDAPL.Execute("UPDATE LINHASCOMPRASSTATUS SET ESTADOTRANS = 'A' WHERE IDLINHASCOMPRAS ='" + dataItem.Cells[1].Text + "'", out rows,
-1);
this.Resultados.DataSource = null;
this.Resultados.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
if (chkR.Checked)
{
try
{
Motor.DSO.BDAPL.Execute("UPDATE LINHASCOMPRASSTATUS SET ESTADOTRANS = 'R' WHERE IDLINHASCOMPRAS ='" + dataItem.Cells[1].Text + "'", out rows, -1);
this.Resultados.DataSource = null;
this.Resultados.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
I see when debugging, that for some reason the checkbox is checked in the row that have the groupheader, and then, in the row that is effectibly selected, the checkbox is not checked.
So, in few words, how can i bypass the groupheader row and only search the checkboxes in the other rows?
Thank you.
EDIT: The error: Conversion failed when converting from a character string to uniqueidentifier.

Filter out the Header (and optionally the footer) rows by checking the TableSection property of the GridViewRow. The syntax may be slightly off (I mostly do VB), but put something like this after your ForEach declaration...
If (dataitem.TableSection != TableRowSection.TableHeader) {
object rows;
//Rest of the code goes here...
}

Related

How to create a label or a text in gridview to overwrite certain cells for certain conditions?

I’m working with asp.net and I have created a grid view as below. When Status text is set to a particular status I want to cover all of the cells, apart from the status text, in that row with a warning.
The data comes from an MQ string and is managed by a separate class. I’m thinking that a row databound event might be the way to go. I’m thinking something like the code below
Gridview:
<asp:GridView runat="server" ID="gridDisc" GridLines="none" AutoGenerateColumns="false" CellPadding="2" HeaderStyle-backColor="#CCEEFF" OnRowDataBound="gridDisc_RowDataBound" >
<AlternatingRowStyle CssClass="ep1" />
<Columns>
<asp:BoundField DataField="StatusText" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPartDesc" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Qty" />
<asp:BoundField DataField="UOI" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblStockDetails" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblDealerInv" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Listprice" />
<asp:BoundField DataField="DiscCode" />
<asp:BoundField DataField="OptiInd" />
<asp:BoundField DataField="Weight" />
<asp:BoundField DataField="ExchangeSurcharge" />
</Columns>
</asp:GridView>
Code behind:
protected void gridDisc_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PartEnquiryLine line = (PartEnquiryLine)e.Row.DataItem;
Label lbl = (Label)e.Row.FindControl("lblStatusDetails");
if (line.StatusText == Text["280"])
{
lbl.Text = Text["290"]
}
But I haven’t been able to find any guidance on how to create a label that would cover specific cells in that row when triggered. I may be way off with this, but how would I do it?
You can do something like below. I am assuming you wanted to use lblStockDetails for showing the warning message since there is no lblStatusDetails column in your grid view.
Use the following code within the if part when you want a warning message to span multiple columns.
if (e.Row.RowType == DataControlRowType.DataRow)
{
PartEnquiryLine line = (PartEnquiryLine)e.Row.DataItem;
Label lbl = (Label)e.Row.FindControl("lblStockDetails");
if (line.StatusText == Text["280"])
{
lbl.Text = Text["290"]
e.Row.Cells[2].Visible = false;
e.Row.Cells[3].Visible = false;
e.Row.Cells[4].ColumnSpan = 9;
e.Row.Cells[5].Visible = false;;
e.Row.Cells[6].Visible = false;
e.Row.Cells[7].Visible = false;
e.Row.Cells[8].Visible = false;
e.Row.Cells[9].Visible = false;;
e.Row.Cells[10].Visible = false;
}

Href in GridView

I just want to ask how can I have different links in my GridView.
Here is my HTML code for my GridView.
<asp:GridView ID="gridsummary" runat="server" AutoGenerateColumns="False"
HorizontalAlign="Left">
<Columns>
<asp:BoundField DataField="sstat" HeaderText="STATUS">
<ItemStyle Width="250px" HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField DataField="ctr" HeaderText="COUNT" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Top" Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewDelivered.aspx'>View</a>" />
</Columns>
<HeaderStyle CssClass="GRIDVIEW_TITLE" />
<RowStyle CssClass="GRIDVIEW_DETAILS" />
</asp:GridView>
Here is my c# code when loading the page.
if (!IsPostBack)
{
dsSummary = dm.MainDash(Session["Username"].ToString(), "");
gridsummary.DataSource = dsSummary.Tables[0];
gridsummary.DataBind();
string sDelivered = string.Empty;
string sNoAirway = string.Empty;
string sIntransit = string.Empty;
string sReturned = string.Empty;
DataTable dt = new DataTable();
dt = dsSummary.Tables[0];
List<string> slistPostal = new List<string>();
foreach (DataRow dr in dt.Rows)
{
if (dr[0].ToString() == "DELIVERED")
{
sDelivered = dr["HTML"].ToString();
Delivered.InnerHtml = sDelivered;
}
if (dr[0].ToString() == "FOR PROCESSING")
{
sNoAirway = dr["HTML"].ToString();
NoAirway.InnerHtml = sNoAirway;
}
if (dr[0].ToString() == "IN TRANSIT")
{
sIntransit = dr["HTML"].ToString();
Intransit.InnerHtml = sIntransit;
}
if (dr[0].ToString() == "RETURNED")
{
sReturned = dr["HTML"].ToString();
Returned.InnerHtml = sReturned;
}
}
}
What I want is something like this:
If I select the first row of my GridView the third BoundField will be this
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewDelivered.aspx'>View</a>" />
If I select the 2nd row the third BoundField will change to this
<asp:BoundField DataField="sstat" HtmlEncode="False" DataFormatString="<a href='webViewForProcessing.aspx'>View</a>" />
When a different row is selected href will be modified depending on the page that I want to load, is there a condition for that?
PS: My stored procedure is quite long so for your reference sstat is equal to the conditions in above.. for example in my SP i have select 'DELIVERED' AS sstat
Use TemplateField not BoundField
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<HyperLink ID="RedirectBtn" runat="server"
OnClick="RedirectBtn_Click" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
You can add whatever you want in OnRowDataBound event of the grid after that. If your RowDataBound event is called Grid_RowDataBound
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null)
return;
DataRowView row = e.Row.DataItem as DataRowView;
HyperLinkbtn = e.Row.FindControl("RedirectBtn") as HyperLink;
b.NavigateUrl = "write your link";
//if you want to open new tab
b.Target="_blank";
}
You are adding the event to the grid like this:
OnRowDataBound="Grid_RowDataBound"
If you want you can make it with a tag, if your href is static and you don't need to make changes for every row.
<asp:TemplateField HeaderText="YourHeaderText">
<ItemTemplate>
<a target='_blank' href='Your link'>Text/a>
</ItemTemplate>
</asp:TemplateField>

Issue with getting CheckBox value in GridView

I have a GridView that contains a CheckBox control. Once the users check the rows that they want, they click a button and I have to update the database for each checked row.
I have the code to iterate trough the gridview rows and look at the checkbox value, but its always false, even if its checked. I do get a reference to the checkbox in ignore but it is always false. What am I missing here?
aspx.cs file:
protected void Ignore_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdNotReceived.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ignore = (CheckBox)row.FindControl("chkIgnore");
if (ignore.Checked)
{
// Update Database
}
}
}
}
.aspx page:
<asp:GridView ID="grdNotReceived" runat="server"
Width="600px"
CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
PagerStyle-CssClass="pgr" AutoGenerateColumns="false">
<AlternatingRowStyle CssClass="alt"/>
<Columns>
<asp:BoundField DataField="Store" HeaderText="Store" />
<asp:BoundField DataField="Dept" HeaderText="Dept" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:BoundField DataField="RefNumber" HeaderText="RefNumber" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Vendor" HeaderText="Vendor" />
<asp:BoundField DataField="Total" HeaderText="Total" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkIgnore" runat="server" Checked="false" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView databind method:
protected void LoadExceptions()
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
If your databinding function ( LoadExceptions() ) is being called somwhere on the page load (like the Load event or class constructor) then it's overriding the changes the user has made in the form.
Don't databind if the page is in post back, you can add an if (!Page.IsPostBack) before calling LoadExceptions() or you can update LoadExceptions() to check it:
protected void LoadExceptions()
{
if (!Page.IsPostBack)
{
Database db = new Database();
SqlCommand sql = new SqlCommand();
sql.CommandText = "getSobeysNotReceived";
this.grdNotReceived.DataSource = db.GetSprocDR(sql);
this.grdNotReceived.DataBind();
db.Close();
}
}

Filtering a GridView with drop downs

I've been stuck on this for too long, and my Google-Fu is failing me. I'm new to C# and .Net, so I'm getting pretty frustrated here.
Here's what I have so far:
A method called GetData populates a DataSet, then I create a DataTable from that.
I bind the DataTable to the GridView, which is then made sortable. The table and sorting work fine, but I need to have drop down filtering on a few of the columns, but I can't get anything to work.
My ASP:
<asp:GridView id="gvEvaluator" Runat="server" Width="750" tooltip="Evaluator Status" AutoGenerateColumns="False"
EnableViewState="true"
HeaderStyle-ForeColor="#000000"
HeaderStyle-BackColor="#CCCCCC"
FooterStyle-ForeColor="#000000"
FooterStyle-BackColor="#CCCCCC"
Font-Size="8pt"
Font-Names="Verdana"
CellSpacing="0"
CellPadding="3"
ShowFooter="true"
AllowSorting="true"
GridLines="Both"
BorderColor="#ffffff"
BackColor="#ffffff"
ItemStyle-HorizontalAlign="Left"
visible="true"
AllowPaging="false"
AllowCustomPaging="false"
OnSorting="GridView_Sorting">
<Columns>
<asp:TemplateField HeaderText="<strong>Term</strong>"
HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Bottom"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="top" >
<HeaderTemplate>
<asp:DropDownList ID="ddlTerm"
runat="server"
visible="true"
OnSelectedIndexChanged="ddlTermChanged"
AutoPostBack="true"
DataSourceID="gvEvaluator">
</asp:DropDownList>
</HeaderTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Dept" HeaderText="Dept" SortExpression="Dept></asp:BoundField>
<asp:BoundField DataField="Course" HeaderText="Course" SortExpression="Course"></asp:BoundField>
<asp:BoundField DataField="Section" HeaderText="Section"></asp:BoundField>
<asp:BoundField DataField="Evaluator" HeaderText="Evaluator" SortExpression="Evaluator"></asp:BoundField>
<asp:BoundField DataField="Type" HeaderText="Evaluator Type"></asp:BoundField>
<asp:BoundField DataField="Email_Address" Visible="false"></asp:BoundField>
<asp:BoundField DataField="Days_Since_Login" HeaderText="Days Since Login"></asp:BoundField>
<asp:BoundField DataField="Required_Work" HeaderText="Required Work" SortExpression="Required_Work"></asp:BoundField>
<asp:BoundField DataField="Total_Assigned" HeaderText="Total Assigned" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_Not_Started" HeaderText="Total Not Started" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_in_Progress" HeaderText="Total in Progress" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_Complete" HeaderText="Total Complete" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="eval_id" Visible="false"></asp:BoundField>
<asp:TemplateField HeaderText="<strong>Need Reminder<strong>" ItemStyle-Width="250px">
<ItemTemplate>
<label for="hyplEvaluator" class="hide">Email Evaluator</label>
<asp:HyperLink ID="hyplEvaluator" runat="server" CssClass="BodyLink" Text='<%# DataBinder.Eval(Container, "DataItem.Need_Reminder")%>' NavigateUrl='' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my C#:
protected void getEvaluatorStatus()
{
try
{
ds = GetData();
DataTable myTable = ds.Tables[0];
if (myTable.Rows.Count != 0)
{
gvEvaluator.DataSource = ds;
gvEvaluator.DataBind();
gvEvaluator.Visible = true;
lblNoAssignment.Visible = false;
}
else
{
lblNoAssignment.Visible = true;
gvEvaluator.Visible = false;
}
//Adds attributes to hyplEmailContact
for (int i = 0; i < gvEvaluator.Rows.Count; i++)
{
string inSenderID = Convert.ToString(meth.decrypt(Session["UserID"].ToString(), Convert.ToString(Session["University"]), Convert.ToString(Session["Department"])));
string inRecptID = Convert.ToString(gvEvaluator.Rows[i].Cells[10].Text);
//custom string of attributes above
string customStr = "inSenderID=" + inSenderID + ",inRecptID=" + inRecptID;
//Adds the NavigateURL for Contact command to pass variables/attributes
HyperLink hyplEmailContact = (HyperLink)gvEvaluator.Rows[i].FindControl("hyplEvaluator");
hyplEmailContact.NavigateUrl = "javascript:openEmailGeneral(" + customStr + ")";
} //End for loop
}
catch (Exception ex)
{
Session["Error_Code"] = ex;
Response.Redirect("../Error.aspx");
}
I'm just a lowly bug squasher, so the only code I personally wrote was creating the GridView (from a DataGrid), the GetData method, making it sortable, and making the data exportable.
Something like this should work:
Handle the ddlTermChanged changed event:
Grab the new selected value in the dropdown list as so
protected void ddlTermChanged(Object sender, EventArgs e) {
var newValue = ddlTerm.SelectedValue;
//see step 3 below
}
Now filter the data and rebind it to the Gridview; something like:
protected void ddlTermChanged(Object sender, EventArgs e) {
var newValue = ddlTerm.SelectedValue;
DataTable t= GetDataByID(newValue);
gvEvaluator.DataSource=t;
gvEvaluator.DataBind();
}
On a separate note, all the transformations you are doing on the Gridview inside the getEvaluatorStatus method should have been handled in the OnRowDataBound event. By doing it the way you did it, every time you rebind the data (as in the case of filtering) you'll have to repeat the code inside the getEvaluatorStatus to do the transformations again. If you do it OnRowDataBound you won't have to repeat code as the event is raised for every row as it is being bound.

Check/Uncheck not working in the paging handled in gridview

I have used the paging in the gridview.
I need the code for check/uncheck in gridview either in server side or client side.
I have tried without paging, it's working. I need it with paging.
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHGrid" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkGrid" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This technique is called maintaining the state of GridView CheckBox in Paging. One method to achieve this is as follows.
Create a Genric List of int or string to store the DataKeys related to Checked rows in it.
At PageIndexChanging before you set the PageIndex to new index. For each rows in GridView,
If checkbox is checked, store the id to the generic list.
If checkbox is unchecked & the ID exist in generic list, remove it from the list.
At RowDataBound event, for each DataRow, check if the DataKeyName is present in the Generic List. If so, find the CheckBox and make it checked.
A simple example with Products Table, Northwind Database is given below
The Markup
<asp:GridView ID="gvProducts" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="ProductID"
OnPageIndexChanging="gvProducts_PageIndexChanging"
OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsProducts" runat="server"
ConnectionString='<%$ ConnectionStrings:NorthwindConnectionString %>'
SelectCommand="SELECT * FROM Products">
</asp:SqlDataSource>
The Code Behind
private List<int> ProductIDs
{
get
{
if (this.ViewState["ProductIDs"] == null)
{
this.ViewState["ProductIDs"] = new List<int>();
}
return this.ViewState["ProductIDs"] as List<int>;
}
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow gvr in gvProducts.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
if (chkSelect.Checked && !this.ProductIDs.Contains(productID))
{
this.ProductIDs.Add(productID);
}
else if (!chkSelect.Checked && this.ProductIDs.Contains(productID))
{
this.ProductIDs.Remove(productID);
}
}
}
}
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow gvr = e.Row;
if (gvr.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect != null)
{
int productID = Convert.ToInt32(gvProducts.DataKeys[gvr.RowIndex]["ProductID"]);
chkSelect.Checked = this.ProductIDs.Contains(productID);
}
}
}

Categories

Resources