I have a GridView where one of the columns is for a display order for the fields where they will be shown on the front end of my website. Instead of going into each record in the edit page and having to change the order this way, it would be handier to be able to click a button and have the whole DisplayOrder (int) editable, therefore making life alot easier. How can this be done?
Try this code :
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>Manager1</asp:ListItem>
<asp:ListItem>Manager2</asp:ListItem>
<asp:ListItem>Manager3</asp:ListItem>
<asp:ListItem>Manager4</asp:ListItem>
</asp:ListBox>
<asp:GridView ID="UserAllocationGrid" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Manager" HeaderText="Manager"
SortExpression="managers" />
<asp:TemplateField HeaderText="Allocation Percentage">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text= '<%# Bind("AllocationPercentage") %>' BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
void fillGV()
{
DataTable UserAllocationTable = new DataTable();
UserAllocationTable.Columns.Add("Manager");
UserAllocationTable.Columns.Add("AllocationPercentage");
// go through listbox1 to find selected managers = selectedManagersList
List<string> selectedManagersListDates = new List<string>();
int counterR = 0;
foreach (ListItem strItem in ListBox1.Items)
{
//selectedManagersListDates.Add(strItem.Value);
DataRow drManagerName = UserAllocationTable.NewRow();
UserAllocationTable.Rows.Add(drManagerName);
UserAllocationTable.Rows[counterR]["Manager"] = strItem.Value;
counterR = counterR + 1;
}
// ViewState["UserAllocationTable"] = UserAllocationTable;
UserAllocationGrid.DataSource = UserAllocationTable;
UserAllocationGrid.DataBind();
}
Use this void in any event I did it in abutton click
protected void Button1_Click(object sender, EventArgs e)
{
fillGV();
}
You can try this using ShowDeleteButton="true" in asp commandfield you can make gridview edidable :-
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
may be help you
You can try below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton = "true">
<Columns>
<asp:BoundField DataField="prodId" HeaderText="Product Id" SortExpression="prodId" ReadOnly = "true" />
<asp:BoundField DataField="prodQuantity" HeaderText="Quantity"
SortExpression="prodQuantity" ReadOnly = "true" />
</Columns>
</asp:GridView>
At Gridview level set AutoGenerateEditButton = "true". This will enable user to edit row.
At Data Field level use ReadOnly = "true" to prevent specific field(in row) from being edited.
Hope this helps.
You can try this, it will give text boxes in column
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>'></asp:Label>
<asp:TextBox ID="Description" runat="server"
Text='<%# Eval("Description") %>' Width="175px"
visible="false"></asp:TextBox>
</ItemTemplate>
This link had the answer I was looking for. If you have a custom data source, must handle Edit each edit event raised by GridView. In my case:
Protected Sub gMaterias_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs) Handles gMaterias.RowCancelingEdit
gMaterias.EditIndex = -1
BindData()
End Sub
Protected Sub gMaterias_RowEditing(sender As Object, e As GridViewEditEventArgs) Handles gMaterias.RowEditing
gMaterias.EditIndex = e.NewEditIndex
BindData()
End Sub
Protected Sub gMaterias_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles gMaterias.RowUpdating
lError.Visible = False
lError.Text = ""
Dim idMateria As Integer = e.Keys(0)
Dim row As GridViewRow = gMaterias.Rows(e.RowIndex)
Dim tbl As DataTable = Session("Materias")
tbl.Rows(row.DataItemIndex)("universidad") = CType(gMaterias.Rows(e.RowIndex).Cells(5).Controls(0), TextBox).Text
Dim calf = CType(gMaterias.Rows(e.RowIndex).Cells(6).Controls(0), TextBox).Text
If IsNumeric(calf) Then
tbl.Rows(row.DataItemIndex)("calificacion") = calf
Else
lError.Visible = True
lError.Text = "La calificación no es válida"
End If
gMaterias.EditIndex = -1
BindData()
End Sub
Related
I have a gridview which I populate from the list data. every row in the gridview has a text box. there is one row within the gridview which I want a dropdown control rather then the textbox. I can't figure out how to change the textbox to dropdown control from a row in the grid.
My gridview below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" style="width:100%;" ShowHeader="false"
CellPadding="3" BackColor="White" ForeColor="Black" Font-Bold="false" GridLines="None"
RowStyle-CssClass="GridRow">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemID" runat="server" Text='<%# Eval("GroupItemTypeID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemCode" runat="server" Text='<%# Eval("GroupItemTypeCode") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="310px" >
<ItemTemplate>
<asp:Label ID="lbl_ItemValuesName" runat="server" Text='<%# Eval("ControlName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="RowWid">
<ItemTemplate>
<asp:Label ID="lbl_IsPercentbased" runat="server" Text='<%# Eval("PercentBasedText") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="70px">
<ItemTemplate>
<asp:CheckBox ID="ChkIsPercent" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void GetItemValues()
{
List<Entities.ItemValues> IValues = new List<Entities.ItemValues>();
IValues = BLL.PriceGroupItemValues.GetAllPriceGroupItemValues();
GridView1.DataSource = IValues;
GridView1.DataBind();
}
You can go for this approach in your case :
Put a TextBox and DropDown both in that TemplateField where your TextBox is currently, and set Visible=false in your Dropdown.
Now in your code-behind, you can use the GridView.RowDataBound event to alternatively display the TextBox or the Dropdown whenever and wherever you require. Something like this :
public void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// set Dropdown visible = true/false as per your requirement.
}
else
{
// set Textboxvisible = true/false as per your requirement.
}
}
This event will fire up for ear row in your GridView and based on the condition that is specified, you can manipulate which control you want to show in that particular row. You can find the dropdown control like this :
foreach (GridViewRow row in GridView1.Rows)
{
categoryName = ((DropDownList)row.FindControl("ddlCategoryName"));
}
Hope this helps.
Use a placeholder control instead of a textbox and programmatically add either a textbox or DDL to the Placeholder control in the rowdatabound event based on your criteria
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
DataKeyNames="user_id">
<Columns>
<asp:BoundField DataField="user_id" HeaderText="user_id" ReadOnly="True" InsertVisible="False"
SortExpression="user_id"></asp:BoundField>
<asp:BoundField DataField="user_logon" HeaderText="user_logon" SortExpression="user_logon">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Sample DataSources
'Primary Datasource to bind to the gridview
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 10 user_id, user_logon from your_user_table"></asp:SqlDataSource>
'Secondary datasource to bind to the ddl
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 5 user_id, user_logon from your_user_table"></asp:SqlDataSource>
Code behind, based on the whether the user_id is odd or even I place one or the other control:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If GridView1.DataKeys(e.Row.RowIndex).Value Mod 2 = 0 Then
Dim tb As New TextBox()
tb.Enabled = False
tb.Text = CType(e.Row.DataItem, DataRowView)("user_logon")
ph.Controls.Add(tb)
Else
Dim ddl As New DropDownList()
ddl.DataSourceID = SqlDataSource2.ID
ddl.DataTextField = "user_logon"
ddl.DataValueField = "user_id"
ph.Controls.Add(ddl)
ddl.DataBind()
End If
End If
End Sub
EDIT based on your Comments:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If CType(e.Row.DataItem, DataRowView)("GroupItemTypeID") ="SUBFREQ" Then
Dim ddl As New DropDownList()
ddl.DataSourceID = <substitute your requirements>
ddl.DataTextField = ...
ddl.DataValueField = ...
ph.Controls.Add(ddl)
ddl.DataBind()
Else
Dim tb As New TextBox()
tb.Enabled = ...whatever...
tb.Text = CType(e.Row.DataItem, DataRowView)("GroupItemTypeID")
ph.Controls.Add(tb)
End If
End If
End Sub
Did some work around with the solution Harvey provided and my existing code. Posting my answer here.
In the gridview, created 2 control and visibility of one control(dropdown) to false
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
<asp:DropDownList ID="ddFrequencyBilling" runat="server" CssClass="form-control" Visible="false"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
In the RowDataBound event of the gridview
if (e.Row.RowType == DataControlRowType.DataRow)
{
//foreach( GridViewRow row in GridView1.Rows)
//{
String ItemCode = (e.Row.FindControl("lbl_ItemCode") as Label).Text;
if ( ItemCode == "SUBFREQ")
{
List<Entities.ItemValues> PGItemValues = new List<Entities.ItemValues>();
TextBox TextBoxtemp = ((TextBox)e.Row.FindControl("txtPrice"));
TextBoxtemp.Visible = false;
Label lbel = ((Label)e.Row.FindControl("lbl_IsPercentbased"));
lbel.Visible = false;
CheckBox chk = ((CheckBox)e.Row.FindControl("ChkIsPercent"));
chk.Visible = false;
DropDownList dd1 = ((DropDownList)e.Row.FindControl("ddFrequencyBilling"));
dd1.Visible = true;
PGItemValues = BLL.PriceGroupItemValues.GetItemValueOnCode(ItemCode, 1);
dd1.DataSource = PGItemValues;
dd1.DataTextField = "IValue";
dd1.DataValueField = "ItemCode";
dd1.DataBind();
}
//}
}
and yes it worked. Thanks alot guys.
What I have
I have a gridview bounded to a some Datasource. Inside that i have added another column ("Resources") explicitly bounded to another datasource.
Code.aspx
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" DataSourceID="EntityDataSource1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" ReadOnly="True" SortExpression="Description" />
<asp:BoundField DataField="TFSId" HeaderText="TFSId" ReadOnly="True" SortExpression="TFSId" />
<asp:CheckBoxField DataField="IsBillable" HeaderText="IsBillable" ReadOnly="True" SortExpression="IsBillable" />
<asp:BoundField DataField="Estimate" HeaderText="Estimate" ReadOnly="True" SortExpression="Estimate" />
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:TemplateField HeaderText="Resources">
<ItemTemplate >
<asp:UpdatePanel ID="updatepanel1" runat="server" >
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="100px"></asp:TextBox>
<asp:PopupControlExtender ID="TextBox1_PopupControlExtender" runat="server"
Enabled="True" TargetControlID="TextBox1"
PopupControlID="Panel1" OffsetY="22">
</asp:PopupControlExtender>
<asp:Panel ID="Panel1" runat="server" Height="116px" Width="145px"
BorderStyle="Solid" BorderWidth="2px" Direction="LeftToRight"
ScrollBars="Auto" BackColor="#CCCCCC" Style="display: none">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="UserId"
DataValueField="UserId" AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:42HNetDbConnectionString %>"
SelectCommand="SELECT DISTINCT [UserId] FROM [Resources]">
</asp:SqlDataSource>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I want:
I have been able to display all the names of resources as soon as user click the textbox. user can select as many resources as he/she wants. I need to achieve following:
1.I want to show the comma separated names of all the resources as soon as the user clicks on the checkboxlist. For that purpose I have created onselectedindexchanged event.
2.I also want some idea that how to remember what user has selected last time as it is not remembering.
What I tried:
Code Behind
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
/*
string name = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
name += CheckBoxList1.Items[i].Text + ",";
}
}
TextBox1.Text = name;*/
}
The real problem is i'm not able to access CheckBoxList inside onselectedindexchanged event.
How to access textbox, label inside update panel from code behind using asp.net web forms seems to be less helpful.
Any help would be appreciated. Thanks!!!
Finally I got it:
Code Behind
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int j = 0; j < GridView1.Rows.Count; j++)
{
UpdatePanel up1 = GridView1.Rows[j].FindControl("updatepanel1") as UpdatePanel;
TextBox tb1 = up1.FindControl("TextBox1") as TextBox;
CheckBoxList cb1 = up1.FindControl("CheckBoxList1") as CheckBoxList;
string name = "";
for (int i = 0; i < cb1.Items.Count; i++)
{
if (cb1.Items[i].Selected)
{
name += cb1.Items[i].Text + ",";
}
}
tb1.Text = name;
}
}
string strVendorId = string.Empty;
var vender = new StringBuilder();
var vendorcollection = cmbVendorId.CheckedItems;
foreach (var item in vendorcollection)
vender.Append(item.Value + ",");
strVendorId = vender.ToString();
if (strVendorId != "")
{
strVendorId = strVendorId.Remove(strVendorId.Length - 1, 1);
}
U can use this code as a reference code for comma separate
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" />
I have color table in my database. When page loads color id and color name and color should displayed in GridView.
datafield="color_Id" contains hex color value. I want to use that hex color code into the back color of the gridview table.
My code is:
<asp:GridView id="GridView1" runat="server" BorderColor="Black" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<columns>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:BoundField DataField="color_Id" HeaderText="Color Id"></asp:BoundField>
<asp:BoundField DataField="color" HeaderText="Color Name"></asp:BoundField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:Label ID="lblColor" BackColor='<%# Eval("color_Id") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
Just put an # before the eval like this. Should work.
BackColor='#<%# Eval("color_Id") %>'
BackColor is a System.Drawing.Color property and not a string property. I'm not certain what magic ASP.NET uses to convert BackColor="#FF00FF", but it doesn't work when you evaluate the string at runtime.
Use the following in your code behind:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim c As Label = e.Row.FindControl("lblColor")
If c IsNot Nothing Then
c.BackColor = System.Drawing.Color.FromName(e.Row.DataItem.color_ID)
End If
End If
End Sub
I done it by referencing codes.
thanks for give little idea for jason.
these are the codes
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string colId="",colr="";
colId = e.Row.Cells[1].Text;
colr = e.Row.Cells[2].Text;
if (colId.Trim() != "Color Id" && colr.Trim() != "Color Name")
{
TextBox t = (TextBox)e.Row.FindControl("txtColor");
if (t != null)
{
t.BackColor = System.Drawing.ColorTranslator.FromHtml(colId);
}
}
}
<asp:GridView id="GridView1" runat="server" BorderColor="Black" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" BackColor="Transparent">
<columns>
<asp:CommandField ShowSelectButton="True"></asp:CommandField>
<asp:BoundField DataField="color_Id" HeaderText="Color Id"></asp:BoundField>
<asp:BoundField DataField="color" HeaderText="Color Name"></asp:BoundField>
<asp:TemplateField HeaderText="Color">
<ItemTemplate>
<asp:TextBox ID="txtColor" runat="server" Enabled="False"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
thank you for view & give me a help to overcome my problem.