fill color from database - c#

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.

Related

Gridview ItemTemplate Checkbox to Check Based On Sql Numeric Feild

I Have a nested grid i want to check the column in grid when datakey is present in another table
Grid is like this
<asp:GridView Width="100%" DataKeyNames="PK_ServiceTypeID" HorizontalAlign="Center" runat="server" OnRowDataBound="gridServiceLocations_RowDataBound" AutoGenerateColumns="false" ID="gridServiceLocations" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" Width="100%" DataKeyNames="PK_ServiceDetailID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Service" HeaderText="Service" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ServiceTypeName" HeaderText="ServiceTypeName" HeaderStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
i have binded this grid from code behind
If I understand I think something like that will be working :
First, you'll need clear data to work with : get the value from your sql column and store it into a string ( or any type you want) array or List, something like that :
//Get your column value from your db
string myValueFromDb = "0000000062,0000000034,0000000016,0000000174,0000000055";
//Split the values into an list of string
myValues = new List<string>(myValueFromDb.Split(','));
//Here you have all your db values stored in the list myValues
But to access to your checkBox you must add an ID.
Like : asp:CheckBox runat="server" ID="checkBox" />
Now you'll need to check every row of your gridview. Something like that :
protected void gridServiceLocations_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != -1)
{
//Get the value of the current row DataKey
string dataKey = grid_view.DataKeys[e.Row.RowIndex].Value.ToString();
//GET THE ROW
GridViewRow row = e.Row;
//Now compare it with your value
if (myValues.Contains(dataKey))
{
//CHECK CASE
//The index of column of the column where the checkbox are (1 here, change it )
CheckBox checkbox = ((CheckBox)row.Cells[1].FindControl("checkBox"));
checkbox.Checked = true;
}
else
{
//UNCHECK CASE
CheckBox checkbox = ((CheckBox)row.Cells[1].FindControl("checkBox"));
checkbox.Checked = false;
}
}
}

Making a column editable in an ASP.net GridView

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

Hidden fields in a grid won't import to a edit form

I've got a grid that only displays one piece of information such as a title. Other fields are hidden. When you click edit a modal popup displays a form and imports the information from the grid for editing. The information in hidden field are not imported though. I don't want to display all the information in the grid because I have only room for the title.
How can I make this work? Thanks. Risho
<asp:GridView ID="gvForum" runat="server" DataSourceID="odsForumApproval" DataKeyNames="id" Width="200px"
RepeatColumns="1" DataKeyField="id" CssClass="gridview"
AutoGenerateColumns="False" GridLines="None" OnSelectedIndexChanged="_OnCommand">
<AlternatingRowStyle CssClass="altbgcolor" />
<Columns>
<asp:BoundField DataField="title" />
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField runat="server" ID="hfId" Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField runat="server" ID="hfDesc" Value='<%# Eval("description") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" Text="Approve" runat="server" onclick="lnkbtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void lnkbtn_Click(object sender, EventArgs e)
{
LinkButton btndetails = sender as LinkButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
lblID.Value = gvrow.Cells[1].Text;
txtTitle.Text = gvrow.Cells[0].Text;
lblMessage.Text = gvrow.Cells[3].Text;
this.ModalPopupExtender1.Show();
}
The Cell-Text is empty if you are using TemplateFields with nested controls . You need to get the reference to the controls and use their appropriate properties(like TextBox.Text or HiddenField.Value). Therefor you can use FindControl on the GridViewRow:
var hfId = (HiddenField)gvrow.FindControl("hfId");
var hfDesc = (HiddenField)gvrow.FindControl("hfDesc");
txtTitle.Text = gvrow.Cells[0].Text;
lblID.Value = hfId.Value;
txtTitle.Text = hfdesc.Value;

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

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