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>
Related
Am developing an ASP Webform App and having some challenges with checkbox Viewstate and Postback.
My App has 2 Gridviews. Gridview has about 8 columns and 3 of those columns has 3 TemplateFields with each TemplateField having its own ASP checkbox with a different IDs. Gridview displays data from an Active Directory which has already been assigned to a user will be updated, deleted, or unchanged. i want to use the checkboxes checked states or values for the updates.
Please see Markup for Gridview A
<asp:GridView ID="gv_ZugeteilteEmailverteiler" runat="server" AllowPaging ="true" PageSize="15" CssClass="table table-striped table-bordered" AutoGenerateColumns="false" Width="100%" BorderColor="#DEBA84" BackColor="Silver" HeaderStyle-Height="40px" OnPreRender="gv_ZugeteilteEmailverteiler_PreRender"
HorizontalAlign="Center" CellPadding="0">
<Columns>
<asp:TemplateField HeaderText="Reihe" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="gruppenname" HeaderText="Gruppenname" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="standort" HeaderText="Standort" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="beschreibung" HeaderText="Beschreibung" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="genehmigt" HeaderText="Genehmigt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="400px"/>
<asp:BoundField DataField="zielobjekt" HeaderText="ZielObjekt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="ACTION_CHECKED" HeaderText="Action_Checked" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px" />
<asp:TemplateField HeaderText="Neu-Hinzufügen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cb_EmailverteilerHinzufuegen" runat="server" AutoPostBack="true" Checked="false" ItemStyle-HorizontalAlign="Center" CssClass="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerHinzufuegen_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Entfernen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="cb_EmailverteilerEntfernen" runat="server" AutoPostBack="true" ItemStyle-HorizontalAlign="Center" CssClass="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerEntfernen_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bestätigen" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cb_EmailverteilerBestaetigen" runat="server" AutoPostBack="true" ItemStyle-HorizontalAlign="Center" class="checkboxClass" onclick="CheckBoxCheck(this);" onchange="return javascript:CheckBoxCheck(this);" OnCheckedChanged="cb_EmailverteilerBestaetigen_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle ForeColor="Black" Font-Bold="True" BackColor="#CCCC00"></HeaderStyle>
</asp:GridView>
The Gridview B also has about 6 columns and one checkbox in a Template field. The Data in Gridview B are Directories from the AD that can be added to the user's list of already given directories shown in Gridview A. Hence when the checkbox in Gridview B is clicked, the entire row selected or checked will be added to Gridview A.
Please see the Markup for Gridview B
<asp:GridView ID="gv_MoeglicheEmailverteiler" runat="server" ClientIDMode="Static"
AutoGenerateColumns="false" BorderColor="#DEBA84" BackColor="Silver" HeaderStyle-Height="40px" OnPreRender="gv_MoeglicheEmailverteiler_PreRender"
HorizontalAlign="Center" CellPadding="3" CssClass="tablesorter">
<Columns>
<asp:TemplateField HeaderText="Reihe" ItemStyle-Width="200px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="gruppenname" HeaderText="Gruppenname" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="standort" HeaderText="Standort" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="beschreibung" HeaderText="Beschreibung" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="genehmigt" HeaderText="Genehmigt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="zielobjekt" HeaderText="ZielObjekt" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px"/>
<asp:BoundField DataField="ACTION_CHECKED" HeaderText="Action_Checked" NullDisplayText="n/a" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="250px" />
<asp:TemplateField ItemStyle-Width="300px" HeaderText="Action" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cb_CheckOneMoglicheverteilerRow" runat="server" ItemStyle-HorizontalAlign="Center" class="checkboxClass" AutoPostBack="true" onclick = "Check_Click(this);" OnCheckedChanged="CheckBox_CheckChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle ForeColor="Black" Font-Bold="True" BackColor="#CCCC00"></HeaderStyle>
</asp:GridView>
PROBLEM: Each of the checkboxes in both Gridviews fires events. Example the Checkbox in Gridview B's Event is to add the checked Row to Gridview A. I managed to save the Gridviews ViewState and retrieve them after every Postback or event and Bind them succesfully.
My problem is, the checkboxes in Gridview A, i cannot or dont know how i could save their checkedstates in a ViewState and restore them after Postback or after an Event or after page refreshes. They all go unchecked after page refreshes or after a Postback.
Here are the methods to add a row from Gridview B to Gridview A and Remove Row from Gridview A
// Create Datatable and save in Viewstate, I was thinking i could add the checkboxes columns to the datatable here as well, but i dont know how to get their values, because the Gridview columns values i get from a database boundfield.
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
if (ViewState["SelectedRecords"] != null)
{
dt = (DataTable)ViewState["SelectedRecords"];
}
else
{
dt.Columns.Add("gruppenname");
dt.Columns.Add("standort");
dt.Columns.Add("beschreibung");
dt.Columns.Add("genehmigt");
dt.Columns.Add("zielobjekt");
dt.Columns.Add("Action_Checked");
dt.AcceptChanges();
}
return dt;
}
// Method to add Row to from Gridview A to Gridview B
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("gruppenname = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["gruppenname"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["standort"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["beschreibung"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["genehmigt"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["zielobjekt"] = gvRow.Cells[5].Text;
dt.Rows[dt.Rows.Count - 1]["Action_Checked"] = gvRow.Cells[6].Text;
dt.AcceptChanges();
}
return dt;
}
// Method to remove Row from Gridview A
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("gruppenname = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
// Now this is how i call them
// Method to Get Data from checked Row in Gridview Moglicheverteiler to add to Gridview Zugeteilte Emailverteiler
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
for (int i = 0; i < gv_MoeglicheEmailverteiler.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gv_MoeglicheEmailverteiler.Rows[i].Cells[6].FindControl("cb_CheckOneMoglicheverteilerRow"); string test = gv_MoeglicheEmailverteiler.Rows[i].Cells[1].Text;
if (gv_ZugeteilteEmailverteiler != null && chk.Checked)
{
for (int j = 0; j < gv_ZugeteilteEmailverteiler.Rows.Count; j++)
{
string actionChecked = gv_ZugeteilteEmailverteiler.Rows[j].Cells[6].Text;
if ((chk.Checked && actionChecked == "Bestaetigen")|| (chk.Checked && actionChecked == "Bestaetigt") || (chk.Checked && actionChecked == "TRUE") || (chk.Checked && actionChecked == "FALSE") || (chk.Checked && actionChecked == "Entfernen"))
{
dt = AddRow(gv_MoeglicheEmailverteiler.Rows[i], dt);
dt = AddRow(gv_ZugeteilteEmailverteiler.Rows[j], dt);
}
else if (chk.Checked)
{
dt = AddRow(gv_MoeglicheEmailverteiler.Rows[i], dt);
}
}
}
}
ViewState["SelectedRecords"] = dt;
}
private void SetData()
{
if (ViewState["SelectedRecords"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
for (int i = 0; i < gv_MoeglicheEmailverteiler.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gv_MoeglicheEmailverteiler.Rows[i].Cells[6].FindControl("cb_CheckOneMoglicheverteilerRow");
if (chk != null)
{
DataRow[] dr = dt.Select("gruppenname = '" + gv_MoeglicheEmailverteiler.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
}
}
}
}
So in short am trying to figure out how i can save the checkboxes values into the viewstate just as i did with the Gridview Columns. Any ideas out there will be really appreciated. Ibeen stocked on the problem for months.
// Bind ZugeteiltGridview For GetData Method
private void BindZugeteilteGridviewForGetDataMethod()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gv_ZugeteilteEmailverteiler.DataSource = dt;
gv_ZugeteilteEmailverteiler.DataBind();
//CheckAddedRowFromMoglicheEmailverteiler();
}
You have AutoPostback=true - this is the problem. Don't do it this way.
Instead, add a button to execute the changes from Grid A to Grid B. You should be able to access the checkbox values then by looping over the GridView rows before they are databound - You might need a hidden field to store the ID of the item on each row. You than should - if you need to - fetch the data for that ID from the datastore rather than try and get it from the GridView. You can try of course but as they are DataBound controls I believe you need to fetch the text of the cell.
Once that is done than you can rebind the grid(s).
Make sure you don't databind the grid A before you loop over it or all you checkboxes will be gone.
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;
}
I am trying to learn how to add an additional nested table inside the firstLevelGrid but I am not succeding. Any help would be appreciated.
Particularly I am doing something wrong in managing the OnRowDataBound when I create the second level grid, both in the markup and the code behind.
This is the code I have that generate the grid and the first level. I have not added my attempts for the second level grid just to avoid to mess up the code.
It is not homework, I am not a professional coder and I am a selflearner.
<div>
<asp:GridView ID="zeroLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="Code" OnRowDataBound="OnRowDataBoundZeroLevel">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="firstLevelPanel" runat="server" Style="display: none">
<asp:GridView ID="firstLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<!-- Here is where I add the second level grid copying the entire block "TemplateFiled" of the firstLevelGrid and renaming it secondLevel...-->
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
and my c# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
zeroLevelGrid.DataSource = GetData("select top 10 * from Table_xx");//top10 only for test purposes
zeroLevelGrid.DataBind();
}
}
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["Test1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBoundZeroLevel(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = zeroLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView firstLevelGrid = e.Row.FindControl("firstLevelGrid") as GridView;
firstLevelGrid.DataSource = GetData(string.Format("IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')) SELECT * from [{0}]", code));
firstLevelGrid.DataBind();
}
}
//here is where I add an OnRowDataBound event copying the above one as OnRowDataBoundFirstLevel
//but then I get lost...
}
I would be glad if someone could indicate me how to add an additional level of nested grid inside the firstLevelGrid identical to it. I would be happy to offer a bounty to get this right but unfortunatelly I do not have enough rep yet. Thank you a lot.
Similart to your firstLevelGrid, you have to declare the third level grid inside the firstLevelGrid as a template column
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="secondLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<%--Your columns go here--%>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
Then handle OnRowDataBound event for the firstLevelGrid
OnRowDataBound="firstLevelGrid_OnRowDataBound"
In the RowDataBound event you can get the grid view, data key and bind the child grid
protected void firstLevelGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView firstLevelGrid = e.Row.NamingContainer as GridView;
string code = firstLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView secondLevelGridView = e.Row.FindControl("secondLevelGrid") as GridView;
secondLevelGridView.DataSource = //GetData
secondLevelGridView.DataBind();
}
}
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.
I have the following gridview:
<asp:GridView ID="gdvReport" runat="server" AutoGenerateColumns="False" DataSourceID="sdseport">
<Columns>
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone">
<ControlStyle Width="250px" />
</asp:BoundField>
<asp:BoundField DataField="ToCall" HeaderText="Foramt" SortExpression="ToCall" />
</Columns>
</asp:GridView>
The second row is a bool in the database, but I do not want to show a checkbox or true\false to the users.
How do I display something like this instead?
0 = Don't Call
1 = Call Us
You could create a TemplateField instead of a BoundField.
<asp:TemplateField HeaderText="Whatever">
<ItemTemplate>
<asp:Literal ID="litTextValue" runat="server" />
</ItemTemplate>
</asp:TemplateField>
You could then put some code inline to display the text that you want or handle the RowDataBound event to do the logic there.
I ended up just using OnRowDataBound for this.
<asp:GridView ID="gdvReport" runat="server" AutoGenerateColumns="False" DataSourceID="sdseport" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone">
<ControlStyle Width="250px" />
</asp:BoundField>
<asp:BoundField DataField="ToCall" HeaderText="Foramt" SortExpression="ToCall" />
</Columns>
</asp:GridView>
protected void OnRowDataBound(object sender, EventArgs e)
{
GridViewRowEventArgs ea = e as GridViewRowEventArgs;
if (ea.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = ea.Row.DataItem as DataRowView;
Object ob = drv["Phone"];
if (!Convert.IsDBNull(ob))
{
bool iParsedValue = false;
if (bool.TryParse(ob.ToString(), out iParsedValue))
{
TableCell cell = ea.Row.Cells[1];
if (iParsedValue == false)
{
cell.Text = "Don't Call";
}
else
{
cell.Text = "Call Us";
}
}
}
}
}
And it is working great now.
I did this and it work
<asp:Literal ID="isActive" runat="server"
Text='<%#Eval("isActive")==DBNull.Value ?
"inactive":Convert.ToBoolean(Eval("isActive"))?"active":"inactive"
%>'></asp:Literal>
This is the important part.
Text='<%#Eval("isActive")==DBNull.Value?"inactive":Convert.ToBoolean(Eval("isActive"))?"active":"inactive" %>'
Hope that helps.
You should do it in the sql instead of doing it here using a CASE statement
such as
CASE ToCall WHEN '1' THEN 'Call' ELSE 'Do not call' END AS ToCall
and then use a simple bound field such as
<asp:BoundField DataField="ToCall" HeaderText="Foramt" SortExpression="ToCall" />