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.
Related
Reference image of the GV
So OnSelectedIndexChanged of the dropdown in 7th cell I want to enable or disable the Remarks column (last column) of that row
Gridview.aspx
<asp:GridView ID="grdassetslist" runat="server" AutoGenerateColumns="false" BackColor="Transparent" BorderColor="Black" BorderStyle="Dashed" BorderWidth="1px" CellPadding="4"
DataKeyNames="ID" AutoGenerateSelectButton="true" CellSpacing="2" OnRowDataBound="grdassetslist_RowDataBound" HeaderStyle-ForeColor="Black" HeaderStyle-BackColor="#66ccff"
OnSelectedIndexChanged="grdassetslist_SelectedIndexChanged" HorizontalAlign="Center" HeaderStyle-CssClass="grd" RowStyle-CssClass="grd" AllowPaging="true" PageSize="15"
OnPageIndexChanged="grdassetslist_PageIndexChanged" OnPageIndexChanging="grdassetslist_PageIndexChanging">
<Columns>
<asp:TemplateField Visible="false" >
<ItemTemplate>
<asp:HiddenField ID="hdnAstID" runat="server" Visible="false" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Asset Category" ReadOnly="true" />
<asp:BoundField DataField="SAPAssetCode" HeaderText="SAP Asset Code" ReadOnly="true" />
<asp:BoundField DataField="ITAssetCode" HeaderText="IT Asset Code" ReadOnly="true" />
<asp:BoundField DataField="Make" HeaderText="Make" ReadOnly="true" />
<asp:BoundField DataField="ModelNo" HeaderText="ModelNo" ReadOnly="true" />
<asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" ReadOnly="true" />
<asp:BoundField DataField="AssetStatus" HeaderText="Current Status" ReadOnly="true" />
<asp:TemplateField HeaderText="Change Status To">
<ItemTemplate>
<asp:DropDownList ID="ddl_each_asset_status" runat="server" Width="100px" Height="25px" CssClass="dd" AutoPostBack="true" OnSelectedIndexChanged="ddl_each_asset_status_SelectedIndexChanged1" CausesValidation="false" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CurrentUser" HeaderText="CurrentUser" ReadOnly="true" />
<asp:TemplateField HeaderText="Remarks for Status change">
<ItemTemplate>
<asp:TextBox ID="txtrmrks" runat="server" placeholder="Remarks (if any)" ReadOnly="true"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Assests" HeaderText="" ReadOnly="true" />--%>
</Columns>
<HeaderStyle HorizontalAlign="Center"/>
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>
GridLoad.apx.cs
con.Open();
DropDownList DropDownList1 = (e.Row.FindControl("ddl_each_asset_status") as DropDownList);
SqlCommand cmd = new SqlCommand("select ID,Code[Title] from tbl_assetstatus (nolock) where ID<>2 and IsActive=1 order by ID", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Title";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Status", "0"));
SelectedIndexChanged event:
protected void ddl_each_asset_status_SelectedIndexChanged1(object sender, EventArgs e)
{
//Code to Enable or Disable the remarks column of that row of which the dropdown was changed?
}
Please add the code for SelectedIndexChanged for this.
Thanks in Advance
If you using GridView, then I doubt this is a .net core application?
And really, to help us out here - try posting at LEAST SOME of your gridviewe markup, as then we not trying to play a game of darts in a room with the lights out.
Assuming a GV like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID"
CssClass="table table=table-hover" Width="800px"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="First name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:TemplateField HeaderText="Select Hotel City">
<ItemTemplate>
<asp:DropDownList ID="cboCity" runat="server" Width="120px" Height="26px"
DataTextField="City"
DataValueField="City"
AutoPostBack="true"
OnSelectedIndexChanged="cboCity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
</Columns>
</asp:GridView>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="lbl1" runat="server" Height="179px" Width="450px" TextMode="MultiLine">
</asp:Label>
</div>
Code to load:
DataTable rstCity = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT City FROM City ORDER BY City";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstCity.Load(cmdSQL.ExecuteReader());
cmdSQL.CommandText =
"SELECT * FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
Ok, and now the code for the combo box (dropdown list). We assume auto-post back, so the code is thus this:
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
string cr = System.Environment.NewLine;
string sResult =
$"Row index = {gRow.RowIndex} \n DataBase PK = {PK} <br/>" +
$" Hotel = {gRow.Cells[3].Text} <br/>" +
$"Combo Box selection = {cboCity.Text}";
lbl1.Text = sResult;
}
and thus we see/get this:
Edit2:
I should also note the following additonal information:
Of course I have to fill/load the drop down.. and that is done in row data bound event. Eg this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView gData = (DataRowView)e.Row.DataItem;
DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
cboCity.DataSource = rstCity;
cboCity.DataBind();
cboCity.Items.Insert(0,new ListItem("Select", ""));
if (gData["City"] != DBNull.Value)
{
cboCity.Text = gData["City"].ToString();
}
}
}
Also, note how I don't care (or bother) with the GV selected index changed event. I really don't need it. I as noted, simple set autopost-back = true.
Last but not least?
you of course cannot build ANY working webforms page if you attemptto load up data in on-load but FORGET to check isPostback.
Since any button click, any post-back, or anything causing a post-back will of course trigger the page load event again, and BEFORE any of your other events. Thus, you need to ALWAYS ensure that you only load up the information one time on page load, since if you re-load the gv, or even a dropdown, then you tend to lose that choice by the user being made.
thus, that all imporant !IsPostBack stub is required for most pages.
Eg this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
next up:
Since the dropdown list has the one grid row, then you are free to get data, hide data, enable or do whatever you please.
Just keep in mind that
For built in "databound" columns, you use the cells[] colleciton.
For any templated control, then you use gRow.FindControl("control name here")
So, since your "goal" in question is to operate on "txtrmrks" then that is a templated column, and thus we have to use findcontrol.
Say, like this:
air code warning!!!
protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList cboCity = (DropDownList)sender;
GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
TextBox txtrmrks = (TextBox)gRow.FindControl("txtrmrks");
if (cboCity.Text == "Banff")
{
// disable the txtrmrks box
txtrmrks.Enabled = false;
}
}
You also not clear if you are going to working the value returned from the cbo box as "id", or "Title"
I suggest this way, and not to use ".Text" of the cbo, but this:
cboCity.SelectedItem.Value (gets value - ID)
cboCity.SelectedItem.Text (gets Text - Title)
if (cboCity.SelectedItem.Text)
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 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();
}
}
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...
}
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" />