How to change GridView Header Style colour for selective columns - c#

I am fairly new to asp.net webforms and I have the following code to generate a grid with two columns,
I separated the columns using colours which I am able to do using e.Row.Cells[0].BackColor = Color.FromArgb(152, 251, 152);and for the second column e.Row.Cells[1].BackColor = Color.FromArgb(60, 179, 113) at the back end
what i am trying to achieve now is to colour the part of the GridView Header that is over the FirstColumn to the same colour as the first column and the second portion of the GridView Header that is over SecondCoumn to the same colour as the second column
Below is m y code
<asp:GridView ID="GridData" CssClass="Gridview" runat="server"
Width="100%" AutoGenerateColumns="False" OnRowDataBound="GridData_RowDataBound" ShowFooter="True">
<Columns>
<asp:TemplateField ItemStyle-Width="120px" HeaderText="ColumnFirst" >
<ItemTemplate>
<asp:Label ID="lblLoanGiven" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalLoanGiven" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="120px" HeaderText="ColumnSecond">
<ItemTemplate>
<asp:Label ID="lblLoanGivenBalance" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotalLoanGivenBalance" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<PagerStyle BackColor="#3C8DBC" ForeColor="White" />
<HeaderStyle BackColor="#3C8DBC" ForeColor="White" />
<FooterStyle BackColor="#007C98" ForeColor="White" CssClass="footer-design" />
</asp:GridView>

GridData.HeaderRow.Cells[1].Style["background-color"] = "#3CB371";
Found the answer the above code colours my 2porions of the GridView headers

Related

Delete Row Using Delete button in ASP GridView

I have a GridView on an ASP. NET web form which is displaying some information from a table in a SQL database. I also have some buttons to delete, update and add new data. However, my delete button doesn't work. I keep getting the error "Object reference not set to an instance of an object."
I will post the function below with the data in the table. Can anyone assist me, please?
<asp:GridView ID="gvFarmer" runat="server"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="5" style="margin-right: 58px"
CellSpacing="1" GridLines="None" AutoGenerateColumns="false" Height="166px" Width="692px" ShowFooter="true" ShowHeaderWhenEmpty="true"
OnRowCommand="gvFarmer_RowCommand" OnRowEditing="gvFarmer_RowEditing" OnRowCancelingEdit="gvFarmer_RowCancelingEdit" OnRowUpdating="gvFarmer_RowUpdating" OnRowDeleting="gvFarmer_RowDeleting">
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
<Columns> <%--Colums are created here --%>
<%-- COLUMN 1--%>
<%-- Creation of template field to hold column names and information for a table--%>
<asp:TemplateField HeaderText="Farmer ID"> <%-- here the filed is created--%>
<ItemTemplate>
<asp:Label Text='<%# Eval("Farmer_Id") %>' runat="server"></asp:Label> <%-- By default the filed will be a label for viewing--%>
<%-- The eval() function will binds the title of colums name in the database to the title in browser. So, if changes are made they are reflected --%>
</ItemTemplate>
<EditItemTemplate> <%-- when the field is clicked on to be eidted, it will be a textbox so the user can interact with--%>
<asp:TextBox ID="txtFarmerID" runat="server" Text='<%# Eval("Farmer_Id") %>'></asp:TextBox>
<%-- The eval() function will binds the title of colums name in the database to the title in browser. So, if changes are made they are reflected --%>
</EditItemTemplate>
<FooterTemplate><%-- This will be the default area from which new records are added to the table--%>
<asp:TextBox ID="txtFarmerIDFooter" runat="server"></asp:TextBox>
<%-- A textbox is used for getting the pieces of information to be added to the table--%>
</FooterTemplate>
</asp:TemplateField><%-- End of first column--%>
<%-- COLUMN 2--%>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFarmerFirstName" runat="server" Text='<%# Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFarmerFirstNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<%-- COLUMN 3--%>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFarmerLastName" runat="server" Text='<%# Eval("LastName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFarmerLastNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
Below is the C# Code for the Delete Function after you click the delete icon:
protected void gvFarmer_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
string InsertQuery = "DELETE FROM Farmer WHERE Farmer_Id = #Farmer_Id";
//parametrized variables are used to prevent sql injection
SqlCommand insert = new SqlCommand(InsertQuery, con);
insert.Parameters.AddWithValue("#Farmer_Id", (gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox).Text.Trim());
//get the info from textbox, trim spaces and store it in appropirate fields in the database
insert.ExecuteNonQuery(); //function executes the insert query
PopulateGridView(); //function is called to show updated view.
lblSuccess.Text = "Record Deleted!";
lb1Error.Text = "";
}//using block ends here
}
catch (Exception ex)
{
lblSuccess.Text = "";
lb1Error.Text = ex.Message;
}//end of try catch
}
The most possible cause is this cast:
gvFarmer.Rows[e.RowIndex].FindControl("txtFarmerID") as TextBox
This cast will return null value if the row type is not DataRow or the control is not found on respective row and throwing NullReferenceException when using Text property. You should try using Cells property:
insert.Parameters.AddWithValue("#Farmer_Id", (gvFarmer.Rows[e.RowIndex].Cells[n].FindControl("txtFarmerID") as TextBox).Text.Trim());
n indicates the column index where txtFarmerID sets up (usually ID column set as index 0).
If it still doesn't work, add DataKeyNames attribute in the markup:
<asp:GridView ID="gvFarmer" runat="server" DataKeyNames="Farmer_Id" ...>
<%-- grid contents --%>
</asp:GridView>
Then try using DataKeys collection property:
insert.Parameters.AddWithValue("#Farmer_Id", gvFarmer.DataKeys[e.RowIndex].Value.ToString().Trim());
I think the latter approach is better because you don't need to find out the control which holds unique value to delete the row, since the key field name is already defined.
Similar issue:
GridView Edit and Delete "Object reference" error

ASP.Net gridview editing - finding a control on a multipage grid view

I have a gridview that has a textbox in one of cells in my aspx file.
After clicking the edit link in the row, I am able to get the control programatically in the rowdatabound event with this:
e.Row.FindControl("controlPlaceholder");
Using the edit index from the edit event works as well.
However, the control is only enabled on the first page of the gridview. On any other page, FindControl() returns null.
What could be the reason for this? Are there any potential solutions to this issue? I've looked for a solution but haven't had any luck with finding someone who has this particular problem.
Markup:
<asp:Panel ID="pnlAccountAssignment" runat="server" CssClass="clsDataPanel" meta:resourcekey="pnlAccountAssignmentResource1">
<asp:GridView ID="gvAccountAssignment" runat="server" AutoGenerateColumns="False"
AllowPaging="true" PageSize="25" OnRowDataBound="gvAccountAssignment_RowDataBound"
OnRowCancelingEdit="gvAccountAssignment_RowCancelingEdit" OnRowEditing="gvAccountAssignment_RowEditing"
OnRowUpdating="gvAccountAssignment_RowUpdating" OnPageIndexChanging="gvAccountAssignment_PageIndexChanging"
OnSorting="gvAccountAssignment_Sorting" AllowSorting="True" meta:resourcekey="gvAccountAssignmentResource1">
<RowStyle BackColor="White" ForeColor="Black" />
<HeaderStyle CssClass="clsGrayBkgCell" HorizontalAlign="Center" VerticalAlign="Bottom" />
<Columns>
...Other Columns...
<asp:TemplateField meta:resourcekey="TemplateFieldResource8">
<ItemStyle CssClass="clsNumber" HorizontalAlign="Left" VerticalAlign="Top" />
<EditItemTemplate>
<asp:TextBox ID="column13PlaceHolder" runat="server" CssClass="clsNormalLabel">
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblprevMonth" runat="server" CssClass="clsNormalLabel"></asp:Label>
</ItemTemplate>
<HeaderTemplate>
<asp:LinkButton runat="server" ID="hypSortGLBal" OnClick="hypSortGLBal_Click"></asp:LinkButton>
</HeaderTemplate>
</asp:TemplateField>
...Other Columns...
</Columns>
<PagerStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
<asp:HiddenField ID="hdnPrepPopulated" runat="server" />
</asp:Panel>

Add new row into Header of GridView

I have a problem with adding a new row with several controls like textBoxes into Header of GridView. When I add them into Header in GridView_RowCreated method with ...
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow r = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableCell tc = new TableCell();
.. they always are put into first row, not second. How can I change it? I want my created row put in second Header Row. I tried to do it by myself, Firstly, I modified ShowHeader into false and add both first and second rows programmatically, but it is wrong way, aspecially when grid has no data to show but it is necessary to show header. I found this discussion similar discussion, but intellisence doesn't know about override PrepareControlHierarchy. I tried to search it with Object browser, and found that this is method of GridView, but I couldn't plug it and test. Maybe somebody knows easier solution for this prob.
I need some assist.
UPDATED!!!
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="username" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None" onrowcreated="GridView1_RowCreated">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="username" SortExpression="username">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Surname" SortExpression="Surname">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Surname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
UPDATED!!!!
Yes, profs you are right, in my case it is the easiest way to put controls in HeaderTemplate. I forgot about it. But I have a little question, how can I add names of columns without adding additional Labels? Here is my code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="username" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None" onrowcreated="GridView1_RowCreated">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField **HeaderText="username"** SortExpression="username">
<HeaderTemplate>
**<asp:Label ID="Label4" runat="server" Text="username"></asp:Label>**<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<HeaderTemplate>
<asp:Label ID="Label4" runat="server" Text="Name"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Surname" SortExpression="Surname">
<HeaderTemplate>
<asp:Label ID="Label4" runat="server" Text="Surname"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Surname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
I marked bold strings. If I leave without Label (just with HeaderText="username") it isn't show me any name in header column. Only if I add Labels it shows my names. What is wrong with it?
Dynamically you would have to add a second header row after every has been databound
Example in VB but you should be able to convert it easily enough.
Private Sub GridView1_DataBound(sender As Object, e As EventArgs) Handles GridView1.DataBound
// Add checks for row count.
// create a new row
Dim gvr As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal)
Dim gvc As TableCell
// Create a new empty cell
gvc = New TableCell()
//add a new TextBox to the cell
gvc.Controls.Add(New TextBox())
// Add the cell to the row
gvr.Cells.Add(gvc)
// repeat above as necessary
// Add row to Gridview at index 1 (0 is bound header)
// GridView1.Controls(0) is the Gridview table
GridView1.Controls(0).Controls.AddAt(1, gvr)
End Sub
The simplest solution is to not attempt to do it in the code behind. Instead utilize the HeaderTemplate for your TemplateFields.
Here is one as an example:
<asp:TemplateField HeaderText="username" SortExpression="username">
<HeaderTemplate>
username
<br />
<asp:TextBox ID="username" runat="server" />
</HeaderTemplate>
<ItemTemplate...
</asp:TemplateField>

When i Check the Checkbox how do I change that specific row style? C# ASP.NET

So i got this gridview on ASP.NET, it is about a gmail client, i made a template field with a check box that is for select several message at the same time, but first when you select a message i want to change the row background color, I already have my CSS but i dont know how to trigger the action or how to know what row was selected in the code. Here is the template of my grid:
<asp:GridView ID="inboxGrid" runat="server"
AutoGenerateColumns="false" CssClass="inbox" ShowHeader="false" BorderStyle="None" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<ItemStyle Width="24" CssClass="check"/>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle CssClass="from" />
<ItemTemplate>
<asp:Label ID="lblFrom" runat="server"
Text = '<%# Eval("From") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle CssClass="subject" />
<ItemTemplate>
<asp:Label ID="lblSubject" runat="server" Text='<%# Eval("Subject") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle CssClass="date" />
<ItemTemplate>
<asp:Label ID="lblFecha" runat="server" Text='<%# Eval("Fecha") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="inbox"/>
</asp:GridView>
Here is a solution using JQuery
Provided you add a CssClass named chk to asp:checkbox
<asp:CheckBox ID="chkSelect" runat="server" CssClass="chk" />
Here is the script
$(document).ready(function () {
$(".chk :checkbox").live("click", function () {
$(this).closest("tr").css("background-color", this.checked ? "#0000FF" : "");
});
});
Try this:
<asp:CheckBox ID="chkSelect" runat="server" OnClick="changeCss(this.id);" />
You can use toggleClass('CssClassName') to toggle the class on checkbox clicks:
function changeCss(ctrlId){
$(ctrlId).parent().parent().toggleClass('check');
}
The hierarchy is tr > td > checkbox, we go reverse to change the css of tr/row.

Edit and update gridview rows on mouse click event

I want to edit and update gridview rows on mouse click event. If the user clicks on a row it should become editable and when he again clicks on the same row it should become uneditable and the changes should be saved.
my gridview looks like:-
<asp:GridView ID="grdexcelsheet" runat="server" AllowPaging="True"
AutoGenerateColumns="False" RowStyle-HorizontalAlign="Left" HorizontalAlign="Center"
onpageindexchanging="grdexcelsheet_PageIndexChanging"
Width = "100%" Height = "100%" Font-Size="Small">
<PagerSettings Position="Bottom" Mode="NextPreviousFirstLast" FirstPageText="First"
LastPageText="Last" NextPageText="Next" PreviousPageText="Prev" PageButtonCount="5" />
<Columns>
<asp:BoundField DataField="SrNo" HeaderText="SrNo" ReadOnly="true" />
<asp:TemplateField HeaderText="CustomerFieldName">
<ItemTemplate>
<asp:Label ID="Label4" Runat="server" Text='<%# Bind("CustomerFieldName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("CustomerFieldName") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyFieldName" HeaderText="CompanyFieldName" ReadOnly="true" />
<asp:BoundField DataField="Usage" HeaderText="Usage" ReadOnly="true" />
</Columns>
</asp:GridView>
There are many ways to do this. You can use AJAX Control Toolkit Modal Popup Extender for updating your grid. Also, you can make use Update Panel from the same toolkit.
If you are willing to use third party controls...please use this which will be very to use
http://obout.com/grid/grid_commands.aspx...

Categories