C# code inside aspx to fill gridview - c#

I have GridView.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="status" HeaderText="status" ItemStyle-Width="100px" > <ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
</Columns>
</asp:GridView>
In codeBehind
GridView1.DataSource = DataTable1;
GridView1.DataBind();
In aspx file I want to write some c# code. For example the following
if status == 0 then set column value equal to 'zero';
If status == 1 then set column value equal to 'one';
How to change
<asp:BoundField DataField="status" HeaderText="status" ItemStyle-Width="100px" > <ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
so that above written algorithm works?
Thanks!

Use templatefields, for example:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<%# ReturnText(Eval("Status")) %>
</ItemTemplate>
</asp:TemplateField>
in C# codebehind
protected string ReturnText(object val)
{
if(val!=null)
{
if(val.ToString().Equals("1")) {return "one"; }
else if(val.ToString().Equals("0")) {return "zero";}
}
return "";
}
Another option is to return text from SQL query:
SELECT STATUS,
CASE STATUS WHEN 1 THEN 'One' WHEN 0 THEN 'Zero' END As Status_Text
FROM YourTable
Then you can bind the column status_text to the boundfield.

Related

How to save ASP checkbox state in Checkstate and retrieve value after postba

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.

Accessing the value of a passed in argument to click event c#

I have a gridview defined like this...
<asp:GridView runat="server" id="gvProjectLineage"
ShowFooter="false"
DataKeyNames="projectLineageID"
AutoGenerateColumns="False"
AllowPaging="false"
AllowSorting="false"
RowStyle-CssClass="shade" CellSpacing="1"
AlternatingRowStyle-CssClass="unshade"
BorderColor="Transparent"
DataSourceID="gvProjectLineageDataSource"
Width="100%">
<HeaderStyle HorizontalAlign="Left" Font-Underline="true"></HeaderStyle>
<Columns>
<asp:BoundField ReadOnly="True"
HeaderText="Lineage ID"
InsertVisible="false"
DataField="projectLineageID"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="false">
</asp:BoundField>
<asp:BoundField ReadOnly="True"
HeaderText="Relationship type"
InsertVisible="false"
DataField="projectRelationshipType"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="true">
</asp:BoundField>
<asp:BoundField ReadOnly="True"
HeaderText="Related Project"
InsertVisible="false"
DataField="projectTitle"
HeaderStyle-CssClass="columnHeader"
ItemStyle-VerticalAlign="Top"
Visible="true">
</asp:BoundField>
<asp:TemplateField ShowHeader="False"
HeaderStyle-Font-Underline="false"
ItemStyle-HorizontalAlign="Left"
FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="btnDelete"
CommandArgument='<%# Eval("projectLineageID") %>'
CommandName="Delete"
runat="server">
<img style="border:none;"
src="/content/images/icon/deleteIcon.png"
title="Delete this lineage" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False"
HeaderStyle-Font-Underline="false"
ItemStyle-HorizontalAlign="Left"
FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="btnDeleteAll"
CommandArgument='<%# Eval("projectLineageID") %>'
runat="server"
OnClick="btnDeleteAll_Click" >
<img style="border:none;"
src="/content/images/icon/deleteIcon.png"
title="Delete this lineage AND it's reciprocal lineage" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>There are currently no relationships identified for this S&T project.</EmptyDataTemplate>
</asp:GridView>
The first "delete" button calls a simple delete query and it works fine to delete the selected row from the table. However, when I call the 2nd delete button ("DeleteAll"), I want to use the [projectLineageID] to find the related lineage records for a project and delete them all at once.
When I call the 2nd delete function "onclick" as follows, I get nothing in column [0].
protected void btnDeleteAll_Click(object sender, EventArgs e)
{
//Delete lineage and reciprocal lineage for relationship types 1 (Transitioned from) and 2 (Transitioned to)
util u = new util();
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string strRelID = grdrow.Cells[0].Text;
int intRelID = System.Convert.ToInt32(grdrow.Cells[0].Text);
string relType = grdrow.Cells[1].Text;
string relProj = grdrow.Cells[2].Text;
Response.Write ("Deleting relationship between " + projectID + " and the project in column 3 " + relID + " " + relType + " " + relProj + " :");
}
How do I get the projectLineageID to pass it to the query?
And, why can't I display it? Even if I try to "convert" it, I get an error telling me the "Input string was not in a correct format."
Thanks,
Bob

Empty column shows when using Hiddenfield in GridView

I have a HiddenField in my GridView. A very small empty column appears, how can I get rid of the empty column?
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:BoundField datafield ="Explicit Lyrics" headertext="Explicit Lyrics"/>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("SongID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the output
I think you added that hidden field to get id later. No need to add and hide a column. Use datakey .
TemplateField in GridView is meant to represent a field that displays custom content in a data-bound control and HiddenField used to store a non-displayed value.
You are creating a custom content column with a non-displayed value ,that leads to create a column with null as represented view for Front end. So If you want to fetch the value on selected index change of GridView then may use Following methods:
Method1: Use Datakey for grideview to store the datacolumn you want in your selecetedIndexchanged method:
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true" DataKeyNames="SongID">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:BoundField datafield ="Explicit Lyrics" headertext="Explicit Lyrics"/>
</Columns>
</asp:GridView>
To access that key on SelectedIndexChanged Method :
int songId= Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex].Values);
Method2: Add hiddenfield within any column you have in your gridview not a special one for it.
<asp:GridView ID="GridView1" autogeneratecolumns="false" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
autogenerateSelectButton="true">
<Columns>
<asp:BoundField datafield ="Song" headertext="Song"/>
<asp:BoundField datafield ="Album" headertext="Album"/>
<asp:BoundField datafield ="Artist" headertext="Artist"/>
<asp:BoundField datafield ="Genre" headertext="Genre"/>
<asp:BoundField datafield ="Price" headertext="Price"/>
<asp:TemplateField headertext="Explicit Lyrics" >
<ItemTemplate>
<asp:Lable runat="server" ID="lblexp" Text='<%# Eval("Explicit Lyrics")%>'>
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("SongID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You could add this:
<style>
.hidden {display:none;}
</style>
And adding these properties to the asp:HiddenField or ItemTemplate element
ItemStyle-CssClass="hidden" and
HeaderStyle-CssClass="hidden :) let me know if it worked.
You can set the CellPadding and CellSpacing attributes of the GridView to zero:
<asp:GridView CellPadding="0" CellSpacing="0" ... >
If you still see the column you can set its width to zero:
<asp:TemplateField ItemStyle-Width="0" HeaderStyle-Width="0" ... >
On Gridview RowDataBound function add the below code to hide the columns you want.
Eg:
In the aspx,
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
In code behind,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[cellno.].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellno.].Visible = false;
}
}

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.

How do I replace a checkbox in gridview with text?

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

Categories

Resources