At the beginning I have to say that I tried to find the answer... And yes I'm new in ASP.Net world :)
I would like to use DropDownList in an EditItemTemplate field in GridView. I found I cannot set parametr SelectedValue. It's missing. When I try to set it in code behind it seems to ddlEditPermissions doesn't exists.
<asp:TemplateField HeaderText="opravneni" SortExpression="opravneni">
<edititemtemplate>
<asp:DropDownList ID="ddlEditPermissions" runat="server" DataSource='<%# getPermissions() %>' OnPreRender="ddlEditPermissions_PreRender"/>
</edititemtemplate>
<insertitemtemplate>
<asp:TextBox ID="tbEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:TextBox>
</insertitemtemplate>
<itemtemplate>
<asp:Label ID="lEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:Label>
</itemtemplate>
I'm really confused. Could anyone advise me?
You can use RowDataBound of the GridView which gets triggered for every GridViewRow after it was constructed and databound:
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
var ddlEditPermissions = (DropDownList)e.Row.FindControl("ddlEditPermissions");
// bind DropDown manually
ddlEditPermissions.DataSource = getPermissions();
ddlEditPermissions.DataTextField = "Permission_Name"; // presumed text-column
ddlEditPermissions.DataValueField = "Permission_ID"; // presumed id-column
ddlEditPermissions.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView; // you might need to change this type, use the debugger then to determine it
ddlEditPermissions.SelectedValue = dr["Permission_ID"].ToString(); // presumed foreign-key-column
}
}
Related
How do I set the selected value in a gridview dropdownlist to what is in the current record like I currently do for a text box.
I am hoping the user can look at the current values and decide if they need to be changed -- this is what I use for a textbox:
<asp:TemplateField HeaderText="Other Notes" SortExpression="Other Notes" HeaderStyle-Wrap="false">
<edititemtemplate>
<asp:TextBox ID="txtOtherNotes" runat="server" Text='<%# Eval("[Other Notes]") %>' DataTextField="Other Notes" DataValueField="Other Notes"></asp:TextBox>
</edititemtemplate>
<itemtemplate>
<asp:Label runat="server" Text='<%# Bind("[Other Notes]") %>' ID="lblOtherNotes"></asp:Label>
</itemtemplate>
</asp:TemplateField>
You will need to use the OnRowDataBound event for that.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if the row is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//find the dropdownlist in the row using findcontrol
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList");
//fill the dropdownlist from code behind if needed
ddl.DataSource = source;
ddl.DataTextField = "key";
ddl.DataValueField = "valee";
ddl.DataBind();
//cast the dataitem back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//set the correct listitem as selected
ddl.SelectedValue = row["myValue"].ToString();
}
}
}
I ended up using:
SelectedValue='<%# Bind("myID") %>'
to display the current record in the ddl.
With the code below, when I click the Edit button, the selectvalue in gridview dropdownlist is retained while at the same time, retaining the rest of the dropdownlist values so user can select a different value.
Protected Sub RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso gvCustomers.EditIndex = e.Row.RowIndex Then
Dim ddlRoles As DropDownList = DirectCast(e.Row.FindControl("ddlRoles"), DropDownList)
Dim query As String = "select RoleId, Roles from ROLES"
Dim cmd As New SqlCommand(query)
ddlRoles.DataSource = GetData(cmd)
ddlRoles.DataTextField = "Roles"
ddlRoles.DataValueField = "RoleId"
ddlRoles.DataBind()
ddlRoles.Items.FindByValue(TryCast(e.Row.FindControl("lblUserRole"), Label).Text).Selected = True
End If
End Sub
'//Markup:
<asp:Label ID="lblUserRole" runat="server" Text='<%# Eval("RoleId")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlRoles" runat = "server">
</asp:DropDownList>
These work fine for gridview.
However, I would like to change the codebehind to regular web form so I can manipulate the layout out better.
In other words, I have the layout like this:
First Name: _____________
Last Name: ______________
Roles: ________________
My understanding is that in gridview, layout is vertical and is not flexible.
We would like our layout to be horizontal.
Thank you in advance for your assistance
You have to use TemplateField and within that template you can specify your layout, which could contain multiple fields, and use different controls for Edit/Insert operations, like in the following sample:
Listing 1.
<asp:TemplateField HeaderText="Toll-Free: Area/Phone #">
<ItemTemplate>
(
<%# DataBinder.Eval( Container.DataItem, "A_TollFree_AreaCode" )%>
)
<%# DataBinder.Eval(Container.DataItem, "A_TollFree_Number")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAreaCode" runat="server"
CssClass="phoneAreaCode" MaxLength="3"
Text='<%# Bind("A_TollFree_AreaCode") %>' />
<asp:TextBox ID="txtPhoneNumber" runat="server"
CssClass="phoneNumber" MaxLength="20"
Text='<%# Bind("A_TollFree_Number") %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtAreaCode" runat="server"
CssClass="phoneAreaCode" MaxLength="3"
Text='<%# Bind("A_TollFree_AreaCode") %>' />
<asp:TextBox ID="txtPhoneNumber" runat="server"
CssClass="phoneNumber" MaxLength="20"
Text='<%# Bind("A_TollFree_Number") %>' />
</EditItemTemplate>
</InsertItemTemplate>
</asp:TemplateField>
Regarding you second question (in comments), please refer to the Listing 2. that demonstrates the general technique of accessing various Controls in GridView:
Listing 2.
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string _strPhone = DataBinder.Eval(e.Row.DataItem, "txtPhoneNumber").ToString();
Button btn = (Button)e.Row.Cells[0].Controls[1];
}
}
catch { }
}
Best Regards,
In asp.net application, I am using grid-view control in that I am binding the data to the label which is in grid-view.
If data is empty then the color of the row should be in red
If not I mean if data is there to bind then the row in green.
This is my code:
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server" Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You need to handle the RowDataBound event, get into the e.Row item, and assign either a CSS class or directly set the background color. I prefer setting a CSS class so you can change the rendering of it without a recompile later.
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Holiday Region">
<ItemTemplate>
<asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind, I had to assume you were using a DataTable as your data source, update the code to fit your data structure:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem;
if (row["Holidaregion"] == null || row["Holidaregion"].ToString().Trim().Length == 0)
{
e.Row.CssClass = "row-empty";
}
else
{
e.Row.CssClass = "row-full";
}
}
You can do it on rowdatabound function of gridview as follows
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//change it according your cell number or find element
if(e.Row.Cells[0].Text != "")
e.Row.BackColor = Color.Green;
else
e.Row.BackColor = Color.Red;
}
}
if(e.Row.RowType == DataControlRowType.DataRow)
{
Control l = e.Row.FindControl("Label1");
((Label)l).BackColor = System.Drawing.Color.Red;
}
Try something like this
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server"
CSSClass='<%# (String.IsNullOrEmply(Eval("Holidaregion")))?"red:green" %>'
Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Edit:
Instead of fighting with grid view inline and code behind stuffs, just use a jQuery and achieve the same in client side
try it this code it is every row in color change with the category wise or filters wise
http://devloper4u.blogspot.in/2013/10/how-to-set-color-in-every-row-on.html
I am using DetailsView which its DefaultMode: insert, and I want to make its checkbox to be checked by default also user can change it to unchecked, but to bind checkbox we should use
Checked='<%# Bind("Cit_Visible") %>'
and this lets the default status of checkbox to be unchecked, so how can I solve this?
You can assign value to text property of checkbox if you want your check box selected at the time of data binding.
<asp:CheckBox ID="chl" runat="Server" Checked="true" Text="<%# Bind('Cit_Visible') %>" />
on code behind you can access text value to save it to in DB
CheckBox MyCheckbox = new CheckBox();
MyCheckbox = (CheckBox)DetailsView1.FindControl("chl");
Response.Write(MyCheckbox.Checked);
When using a DetailsView data control and you have checkbox values you may be starting with an asp:CheckBoxField which handles all the display modes for you. If you want to keep the checkbox binding but also set the default to checked perhaps for an insert you can do the following.
Convert the field to a TemplateField which can be done through the design view of visual studio or manually by replacing this type of block..
<asp:CheckBoxField DataField="Information" HeaderText="Information" SortExpression="Information" />
with a block of code like this
<asp:TemplateField HeaderText="Information" SortExpression="Information">
<EditItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
</InsertItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
Then to set the checkbox default value to be checked you can do this in the code-behind
Protected Sub dvInformation_PreRender(sender As Object, e As EventArgs) Handles dvInformation.PreRender
If CType(sender, DetailsView).CurrentMode = DetailsViewMode.Insert Then
Dim chk As Object = CType(sender, DetailsView).FindControl("chkInformation")
If chk IsNot Nothing AndAlso chk.GetType Is GetType(CheckBox) Then
CType(chk, CheckBox).Checked = True
End If
End If
End Sub
C# (Converted from VB
protected void dvInformation_PreRender(object sender, EventArgs e)
{
if (((DetailsView)sender).CurrentMode == DetailsViewMode.Insert) {
object chk = ((DetailsView)sender).FindControl("chkInformation");
if (chk != null && object.ReferenceEquals(chk.GetType(), typeof(CheckBox))) {
((CheckBox)chk).Checked = true;
}
}
}
This is obviously best when the supporting database value is a non-null bit field
Use TemplateField:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" OnInit="chk1_Init" Checked='<%# Bind("Cit_Visible") %>' />
</ItemTemplate>
</asp:TemplateField>
Set the checkbox default value in the Init method:
protected void chk1_Init(object sender, EventArgs e)
{
((CheckBox)sender).Checked = true;
}
here is my problem:
I've got a repeater on my asp.net (VB):
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Question_Number") %>' />
<%#Eval("Question_Desc")%>
Now what I want to do is, check a value that I haven't used called "Question_Type" which could be = 1, 2 or 3 depending if it is multiple choice, short answer, etc.
I have tried this:
<%
if Eval("Question_type") = 1 then
Response.Write(" <asp:RadioButton runat=""server"">test1</asp:RadioButton>")
Response.Write(" <asp:RadioButton runat=""server"">test2</asp:RadioButton>")
Response.Write(" <asp:RadioButton runat=""server"">test3</asp:RadioButton>")
end if
%>
and I get this error:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
HOW can I use this value in a if statement???
You are going to need to handle the ItemDataBound event and manually handle the values there.
Here is how I might approach the problem given this repeater:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="HandleQuestionType">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Question_Number") %>' />
<%#Eval("Question_Desc")%>
<asp:PlaceHolder ID="phQuestions" runat="server" />
</ItemTemplate>
</asp:Repeater>
Here is my event handler for getting the possible answers to a radio button list:
protected void HandleQuestionType(object sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var question = e.Item.DataItem as Question;
var placeHolder = e.Item.FindControl("phQuestions") as PlaceHolder;
if(question != null && placeHolder != null)
{
if(question.Question_Type == QuestionTypeEnum.MultipleChoice)
{
var radioList = new RadioButtonList
{
DataTextField = "Answer",
DataValueField = "ID",
DataSource = GetPossibleAnswers()
};
radioList.DataBind();
placeHolder.Controls.Add(radioList);
}
}
}
}