How do I replace a checkbox in gridview with text? - c#

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

Related

C# GridViewRow FindControl get/pass values

I have an asp:linkbutton. When it's pressed I want to get a list of DetailID's based on which of the checkboxes in my GridView are checked. I have a lblTesting to see the list of DetailID's that I'm generating. My goal is to get a list of DetailID's that I pass to an edit page.
I have looked at several examples on Stack Overflow but I cannot get any value other than the checkbox is checked.
Here is the link I have at the top of my page:
<span style="float:right;"><asp:Linkbutton ID="getURLLink" runat="server" Text="Edit Die Detail" OnClick="GetLink"></asp:Linkbutton></span>
<asp:Label runat="server" ID="lblTesting"></asp:Label>
Here is my GridView:
<asp:GridView ID="DieListDetailGridView" runat="server" AutoGenerateColumns="false" OnRowDataBound="DieListDetailGridView_RowDataBound" DataKeyNames="DieID" HeaderStyle-HorizontalAlign="Center" HorizontalAlign="Center" ForeColor="#333333" GridLines="Both">
<RowStyle BackColor="#F5F5DC" />
<AlternatingRowStyle BackColor = "White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Edit" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DieNum" HeaderText="Die Number" />
<asp:BoundField DataField="DieID" HeaderText="Die ID" Visible="false" />
<asp:BoundField DataField="DetailID" HeaderText="Detail ID" Visible="false" />
<asp:HyperLinkField DataTextField="DetailNum" HeaderText="Detail Number" DataNavigateUrlFields="DetailID" DataNavigateUrlFormatString="~/Tooling/DieDetail.aspx?DetailID={0}" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="MaterialType" HeaderText="Material Type" />
<asp:BoundField DataField="Hardness" HeaderText="Hardness" />
<asp:BoundField DataField="MinSpares" HeaderText="Min Spares" />
<asp:BoundField DataField="MaxSpares" HeaderText="Max Spares" />
<asp:BoundField DataField="CurrentSpares" HeaderText="Current Spares" />
<asp:BoundField DataField="DetailNotes" HeaderText="Detail Notes" />
</Columns>
</asp:GridView>
And my GetLink function:
protected void GetLink(object sender, EventArgs e)
{
// start off empty
string DetailIDList = "";
foreach (GridViewRow row in DieListDetailGridView.Rows) {
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkBox = (row.Cells[0].FindControl("chkBox") as CheckBox);
string DetailID = row.Cells[3].Text;
if (chkBox.Checked)
{
DetailIDList = DetailIDList + DetailID + ",";
}
}
}
// Remove the last , from the list
DetailIDList = DetailIDList.Remove(DetailIDList.Length - 1, 1);
// comma delimeted list of checked Detail ID's
lblTesting.Text = DetailIDList;
//Response.Redirect("~/Tooling/DieDetail.aspx?DetailIDList=");
}
I can't figure out why my DetailID is empty.
I've tried doing row.Cells[0].FindControl("DetailID") but that also didn't work.
What I am expecting to get from the DetailID are integers like "28925", "16423" etc.
I was asked to not show the column on the page, which is why visible = false. I still need to reference the ID to pass it to the edit page. I need to do the same edit to multiple Detail ID's.
What am I doing wrong?
The answer to having a list of ID's even though the datafield is set to not be visible was found on another StackOverflow question: ASP.NET: GridView value set to null when column is not visible
The answer was to remove the "Visible=false" from the GridView and on each row created (after the column has the data added for the row) make it not visible.
This code fixed my issue:
protected void DieListDetailGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[2].Visible = false;
e.Row.Cells[3].Visible = false;
}

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;
}

GridView Row checkboxes

I have a gridview in my .NET web app:-
<asp:GridView ID="gvwQueues" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="gvwQueues_PageIndexChanging"
PageSize="5" Width="577px">
<Columns>
<asp:BoundField DataField="Text" HeaderText="Text">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ItemNumber" HeaderText="Item Number">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Directory" HeaderText="Directory">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:CheckBox ID="Yes" runat="server" Text = "Yes" />
<asp:CheckBox ID="No" runat="server" Text = "No"/>
<%-- <asp:CheckBoxList ID="IsActive" runat="server">
<asp:ListItem>Yes.</asp:ListItem>
<asp:ListItem>No.</asp:ListItem>
</asp:CheckBoxList>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now I want to use the checkboxes:- "yes" or "no" to call appropriate functions on the server side that would make each item on the gridview row "Active" or "inactive".
Active means the item shows up for all users, Inactive means the item doesnt show up for any users, except for the admin.
Two modifications might me needed to make your logic work.
a. Try using Radiobutton in the place of using Check Boxes so that the user will be able to select ONLY ONE OPTION either 'Yes' or 'No'. Also note you need group these radio buttons like below to let only one of these radio buttons selectable. So replace your 'IsActive' template field with below:
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:RadioButton ID="yesRadioButton" runat="server" Text="Yes" GroupName="IsActiveGroup" OnCheckedChanged="RadioButtonIsActive_CheckedChanged" />
<asp:RadioButton ID="noRadioButton" runat="server" Text="No" GroupName="IsActiveGroup" OnCheckedChanged="RadioButtonIsActive_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
And assign both of its CheckChanged event to RadioButtonIsActive_CheckedChanged method.
b. Below is the code for the Code behind mehtod RadioButtonIsActive_CheckedChanged
protected void RadioButtonIsActive_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvwQueues.Rows)
{
RadioButton yesRadioButton = (RadioButton)row.FindControl("yesRadioButton");
if (yesRadioButton.Checked)
{
//Make Items Active
}
else
{
//Make Items Inactive
}
}
}
Let me know in case of any queries.
Do you want the check box to call a function when it changes?
Then all you need to do is add OnCheckedChanged
<asp:CheckBox ID="chkStatus" runat="server" Text = "Yes"
OnCheckedChanged="chkStatus_OnCheckedChanged"/>
Serverside you write the function you want it to do
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
//Make active inactive
}
Out side of this are you asking about roles, or binding to a grid?
you can use DataKeyNames for the grid view.
try this once.
<asp:GridView ID="gvwQueues" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="gvwQueues_PageIndexChanging"
PageSize="5" Width="577px" DataKeyNames="ItemNumber">
<Columns>
<asp:BoundField DataField="Text" HeaderText="Text">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ItemNumber" HeaderText="Item Number">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Directory" HeaderText="Directory">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:CheckBox ID="chkYes" runat="server" Text="Yes" OnCheckedChanged="YesOrNo_OnCheckedChanged"
AutoPostBack="true" />
<asp:CheckBox ID="chkNo" runat="server" Text="No" OnCheckedChanged="YesOrNo_OnCheckedChanged"
AutoPostBack="true" />
<%-- <asp:CheckBoxList ID="IsActive" runat="server">
<asp:ListItem>Yes.</asp:ListItem>
<asp:ListItem>No.</asp:ListItem>
</asp:CheckBoxList>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And you can catch the Item Number using ClientID of sender argument
protected void YesOrNo_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkSender = (CheckBox)sender;
foreach (GridViewRow gvRow in gvwQueues.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
CheckBox chkYes = (CheckBox)gvRow.FindControl("chkYes");
CheckBox chkNo = (CheckBox)gvRow.FindControl("chkNo");
if (chkSender.ClientID == chkYes.ClientID || chkSender.ClientID == chkNo.ClientID)
{
int ItemId = Convert.ToInt32(gvwQueues.DataKeys[gvRow.RowIndex].Value);//here is the item number
if (chkNo.Checked)
{
chkYes.Checked = false;
//code to inactive
}
else if (chkYes.Checked)
{
chkNo.Checked = false;
//code to activate
}
}
}
}
}
One more suggestion is better to use Radiobuttons instead of Checkboxes.
You need to handle many conditions by using Checkboxes in your case.

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 to edit an entire column for all rows asp:GridView

So I have google'd and searched stackoverflow, and now my brain is overloaded. I am a novice at asp.net, but getting the hang of it.
My current requirement is to have a gridview where upon load, 1 column for all rows is immediately placed into edit mode. I used this question and code to get me going:
Allowing one column to be edited but not another
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
autogenerateeditbutton="true"
allowpaging="true"
datakeynames="CustomerID"
runat="server">
<columns>
<asp:boundfield datafield="CustomerID" readonly="true" headertext="Customer ID"/>
<asp:boundfield datafield="CompanyName" readonly="true" headertext="Customer Name"/>
<asp:boundfield datafield="Address" headertext="Address"/>
<asp:boundfield datafield="City" headertext="City"/>
<asp:boundfield datafield="PostalCode" headertext="ZIP Code"/>
</columns>
</asp:gridview>
I have searched and found a few good solutions, however, I do not fully understand them and have been unsuccesful at implementing them. They are:
Edit/Update a single GridView field
Put multiple rows of a gridview into edit mode
So my question is, how would you go about placing a column, (e.g, ZIP Code) into edit mode for all rows at the same time?
All help is appreciated!
Thanks!
Stephen
You won't be able to use the built-in edit functionality, but you can achieve this by loading the column in edit mode using a TemplateField:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SomeColumn") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SomeOtherColumn" HeaderText="Foo" />
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Update" CommandArgument='<%# Container.ItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = GridView1.Rows[(int)e.CommandArgument];
if (row != null)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}
EDIT: Putting a button outside of the GridView, you would update like this:
<asp:GridView>
...
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txt = row.FindControl("TextBox1") as TextBox;
if (txt != null)
{
//get the value from the textbox
string value = txt.Text;
}
}
}

Categories

Resources