Change appearance TemplateField from C # - c#

Add this to a GridView and now I would like cambial the background color or text showing from code
How can I do it?
<asp:TemplateField HeaderText="01">
<EditItemTemplate>
<asp:DropDownList ID="falta1" runat="server" > </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("c1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

Welcome to stackoverflow. How about...
<asp:TemplateField HeaderText="Type" ControlStyle-BackColor="Black">
You can just hit the space bar within the control tag to see a list of options for different properties, like ControlStyle.
On a side note, you'll get better responses if you post things you've already tried along with your question.

In the code behind, you have to access the label using FindControl in RowDataBound event and then change the color,text of the label.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label oLabel = (Label)e.Row.FindControl("Label1");
if(oLabel != null)
{
//oLabel.BackColor = System.Drawing.Color.Red;//See below for cambial
oLabel.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFCC99");
oLabel.Text = "MyText";
}
}
}

Related

GridView onRowUpdating Event access to textBox

I got i strange situations.
This is a part of the ascx code of my gridview
<asp:gridview ID="grdBooks" class="grdBooks" runat="server" width="100%" DataKeyNames="RecId,RefAuthorsRecId,RefBooksTypeRecId" autogeneratecolumns="false" onDataBound="grdBooks_dataBound" onPreRender="grdBooks_preRender" onrowediting="grdBooks_RowEdit" onrowupdating="grbBooks_onRowUpdating" onrowupdated="grdBooks_onUpdated" autogenerateeditbutton="true" onrowcancelingedit="grdBooks_onCancelingEdit">
<Columns>
<asp:TemplateField HeaderText="Title">
<EditItemTemplate>
<asp:TextBox ID="txtgrdTitle" runat="server" width="200px"></asp:TextBox>
<asp:Label ID="lblgrdTitle2" runat="server" visible="false" Text='<%# Eval("Title") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblgrdTitle" runat="server" Text='<%# Bind("Title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>.....
This is a part of the "onRowEdit" and "onRowUpdating"
protected void grdBooks_RowEdit(object sender, GridViewEditEventArgs e)
{
grdBooks.EditIndex = e.NewEditIndex;
grdBooks.DataSource = book;
grdBooks.DataBind();
TextBox txtTitle = grdBooks.Rows[e.NewEditIndex].FindControl("txtgrdTitle") as TextBox;
Label lblTitle = grdBooks.Rows[e.NewEditIndex].FindControl("lblgrdTitle") as Label;
txtTitle.Text = lblTitle.Text;
}
protected void grbBooks_onRowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtTitle = grdBooks.Rows[e.RowIndex].FindControl("txtgrdTitle") as TextBox;
....
}
The problem is:
the rowEdit works fine, change all the row of the grid in editable textboxes. The problem is that i write something in the text boxes and when i press "update" and go into the "onRowUpdate" method i haven't the new text(that i have inserted) in the textbox object that i have initialize. I got the old one.
(as u see now i use a not visible label in the editTemplate that carry the value of the original Title. Before i had Eval("title") on the textbox text but i thought that this was the probl so i try this other way)
As your datasource is book.Get the currentrow of the datatable and update values in that row.Then bind the grid again.
GridViewRow gridEditRow = this.grdBooks.Rows[e.RowIndex];
DataRow CurentRow = book.Rows[gridEditRow.DataItemIndex];
CurentRow["Title"] = (gridEditRow.FindControl("txtgrdTitle") as TextBox).Text;

Cannot find gridview EditItemTemplate in code behind

I am trying to modify the content of a TextBox in the OnRowEditing event of the gridview but I cannot seem to find the TextBox control in code behind.
The field in aspx:
<asp:TemplateField HeaderText="AssignTo" SortExpression="AssignTo">
<EditItemTemplate>
<asp:TextBox ID="txtAssignTo" runat="server" Text='<%# Bind("AssignTo") %>' ClientIDMode="Static"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("AssignTo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Trying to find it in code behind:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow grow = GridView1.Rows[e.NewEditIndex];
TextBox txt = grow.FindControl("txtAssignTo") as TextBox;
}
The txt variable is always null. Not sure what I am missing here.
You have to bind the gridview after you set the editindex (call its DataBind() method)

Get Eval value from Gridview from code behind

I have a gridview that loads from a database that has several TemplateFields. How do I retrieve the Eval value from code behind? In other words I need the template field name for that column.
I want to get "Registrations" and store it in a variable.
<asp:TemplateField HeaderText="REG" SortExpression="Registrations">
<EditItemTemplate>
<asp:CheckBox ID="cbRegEdit" runat="server" Checked='<%# (int)Eval("Registrations") == 1 %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReg" runat="server" Enabled="false" Checked='<%# (int)Eval("Registrations") == 1 %>'>
</asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
You have to hook to OnRowDataBound and do something like:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var registrations = ((YourType)e.Row.DataItem).Registrations;
//do something
}
}
Your GridView would then have to be:
<asp:GridView OnRowDataBound="GridView1_RowDataBound" ...
Probably the easiest way is to assign a datakey to your gridview.
An example would be like this:
<asp:Gridview ID="gvExample" runat="server" DataKeyNames="Registrations">
Then in the code behind all you need is the row index and you can do the following:
gvExample.Datakeys(rowindex).value
CheckBox CBreg = (Page.FindControl("cbReg") as CheckBox);
bool Reg = CBreg.Checked; //Reg value stored
You may need to change Page.FindControl to your TemplateField control ID if you cannot find the control this way.

transfer data from gridview to another webform in asp.net using c#?

i have a gridview like this :
<asp:GridView ID="wbsdataGV1" runat="server" Width="790px" AutoGenerateColumns="False"
OnSelectedIndexChanged="wbsdataGV1_SelectionChanged">
<Columns>
<asp:TemplateField HeaderText="WBS Code">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("WBSCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%# Eval("Description") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Territory Code">
<ItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%# Eval("TerritoryCode") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="TextBox9" runat="server" Text='<%# Eval("AmountReleased") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
when i am clicking on the linkbutton i want that data and i will transfer that to another aspx from .. through
protected void wbsdataGV1_SelectionChanged(object sender, EventArgs e)
{
//Some code ;
}
now my question is how i can get that data by clicking the linkbutton on gridview ? i can transfer the data by querystring or session variable or hidden text field ... but my concern is that how can i get the exact clicked data...
any help?
Define the DataKeys attribute to the be primary key of your data (here I assume you have a row identifier called "ID".
<asp:GridView ... DataKeys="ID">
... existing markup
</asp:GridView>
In wbsdataGV1_SelectionChanged, get back the ID of the row the user clicked like this:
int rowID = (int)this.wbsdataGV1.SelectedDataKey.Value;
Then redirect to another page like this, passing just the ID:
Response.Redirect("anotherpage.aspx?id=" + rowID);
Then in your other page:
protected void Page_Load(object s, EventArgs e)
{
if (!Page.IsPostback)
{
int rowID = int.Parse(Request.QueryString["id"]);
// do something with the ID of the row, like go and look
// up JUST that row again
}
}
Bonus - to make the whole row clickable, avoiding the need for a CommandButton, do this:
<script language="javascript" type="text/javascript">
var oldColour = null;
function rowMouseover(o) {
o.style.cursor = 'pointer';
oldColour = o.style.backgroundColor;
o.style.backgroundColor = '#dddddd';
}
function rowMouseout(o) {
o.style.backgroundColor = oldColour;
}
</script>
<asp:GridView ... OnRowCreated="grid_RowCreated" />
protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink(
this.grid,
"Select$" + e.Row.RowIndex);
e.Row.Attributes["onmouseover"] = "rowMouseover(this);";
e.Row.Attributes["onmouseout"] = "rowMouseout(this);";
}
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < grid.Rows.Count; i++)
Page.ClientScript.RegisterForEventValidation(grid.UniqueID, "Select$" + i);
base.Render(writer);
}
You could pass the ID via the Session object, but you'd get odd behaviour with more than one browser window doing the same operation at the same time (depending on the browser). This would be hard for a user to tamper with.
You could pass the ID via Request.Form too, that would hide it from trivial user fiddling but doesn't add any true security.
Protip: don't just dump massive objects into the Session variable. It's lazy, error prone, and doesn't scale.

ASP.NET GridView RowCommand TextBox empty

Hi I have a grid view with a textbox in each row that im trying to get the value of in the RowCommand event. The below code works fine for all rows expect the first one. The textbox.text value for the first row in always empty.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_OnRowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
Title <%# Eval("Title")%>
<asp:TextBox ID="TextBoxAddPost" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("postId") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
bindGridView();
}
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddPost")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox textBox = (TextBox)row.FindControl("TextBoxAddPost");
//Empty for first row but works for all others
Debug.WriteLine("row: " + row.RowIndex + ", textBox:" + textBox.Text.Trim());
GridView1.DataBind();
}
}
The above code has been simplified for illustration purposes. Each row actually contains a child gridview, hence why in need the text box in each row. I fear that the binding in the page_load is overwriting the value of the text box, however, without the page_load binding, the rowCommand Event is not fired.
I find i a bit strange the it works fine for all rows except the first.
For getting data from textbox, You have to set text property first by putting below code.
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>
It will definitely give value from textbox.
Either way, You can also set datakeynames property of gridview.Click here for datakeynames
I tried this and it works fine,GridView1_OnRowCommand fires by clicking on LinkButtonAddPost:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("ID") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and change your page_load event like this:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = Data.RequestPaymentDB.GetRequestPaymentByRequestID(9208060001);
GridView1.DataBind();
}
compare your code with mine.

Categories