How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Related
I have seen multiple posts regarding this subject and the answer is pretty much the same. To set the selecteditem programmatically use the following code:
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
My scenario is slightly different. I'm trying to set the value of a dropdownlist in a gridview.
I am able to populate the dropdownlist, but not able to set the selecteditem or selectedindex.
Gridview
<asp:GridView ID="gvSubject" runat="server"
CssClass="table table-striped clientTblEnabled"
OnRowDataBound="gvSubject_RowDataBound"
AutoGenerateColumns="false"
OnPreRender="gvSubject_PreRender"
GridLines="Both" PageSize="50">
<Columns>
<asp:TemplateField HeaderText="Subject Date">
<ItemTemplate>
<asp:Label ID="lblSubjectDate" runat="server" Text='<%# Bind("SubjectDateTime", "{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblSubject" runat="server" Text='<%# Bind("SubjectDesc") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlSubject" runat="server" CssClass="input-xlarge controls"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Results found
</EmptyDataTemplate>
</asp:GridView>
Populate dropdownlist
protected void gvSubject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlSubject = e.Row.FindControl("ddlSubject") as DropDownList;
if (ddlSubject != null)
{
DataSet ds = GetControlData("ddlSubject");
ddlSubject.DataSource = ds.Tables[8];
ddlSubject.DataTextField = "SubjectDesc";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
ddlSubject.Items.FindByValue((e.Row.FindControl("lblSubject") as Label).Text).Selected = true;
}
}
}
lblSubject is populated by another query in GetControlData().
When the debugger gets to the ddlSubject.Items.FindByValue code, I get a NullReferenceException even though lblSubject has a value.
I wonder if I need to change the gridview event for which I'm loading the data.
I think what you're probably after here is FindByText, not FindByValue. The value of the item will be the SubjectID column, whereas the text of the item will match the text of the label.
I am working on Asp.net and stuck in middle.
I have a gridview with template field.Gridview have 3 columns and I want to pass value of two columns to server Side.
Scenario-On Clicking lnkRemove(LinkButton),the GUID should be passed(which is getting passed in Command arguement) and also the value of SEQ_NBR column(passing this value is problem for me)
I am trying with Hidden field but how to get hiiden field value in Server Side code(i.e Deletedata).
Code
<asp:GridView>
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "SEQ_NBR">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("SEQ_NBR") %>' />
<asp:Label ID="SEQ_NBR" runat="server"
Text='<%# Eval("SEQ_NBR")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="SEQ_NBR" runat="server" ReadOnly="true" Text="Auto generated"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("GUID")%>'
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" OnClick = "Deletedata"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my server side code is:
protected void Deletedata(object sender, EventArgs e)
{
//I want Hiddden field value here;I tried below code but not working.Any suggestion .
chkSelect = GridView.Controls[0].Controls[0].FindControl("HiddenField1");
}
Don't use
GridView.Controls[0].Controls[0].FindControl("HiddenField1");
but on the GridViewRow since that is the NamingContainer:
GridView.Rows[0].FindControl("HiddenField1");
But in this case you want to find the hiddenfield from the LinkButton's click-event. Therefore use following approach. The LinkButton's NamingContainer is the GridViewRow:
protected void Deletedata(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton) sender;
GridViewRow row = (GridViewRow) lnkRemove.NamingContainer;
HiddenField hf = (HiddenField) row.FindControl("HiddenField1");
string seqNbr = hf.Value; // voilĂ
}
Try this one
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
GridView.SelectedIndex = row.RowIndex;
var HiddenField= GridView.Rows[gridMain.SelectedIndex].FindControl("HiddenField1") as HtmlInputHidden;
if (HiddenField!= null)
{
sting strValue = HiddenField.Value;
}
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.
I'm stuck and have no idea what to do, can you help me please?
I have this grid in page markup
<asp:GridView ID="gridEmployees" runat="server"
AllowPaging="True"
AllowSorting="<%# AllowSorting %>"
OnPageIndexChanging="grdView_PageIndexChanging"
OnSorting="gridEmployees_Sorting"
OnRowEditing="gridEmployees_RowEditing"
OnRowUpdating="gridEmployees_RowUpdating"
OnRowCancelingEdit="gridEmployees_RowCancelingEdit"
OnRowUpdated="gridEmployees_RowUpdated"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Full name" SortExpression="FullName">
<ItemTemplate>
<asp:Label runat="server" ID="lbSalary" Width="200px" Text='<%# Eval("FullName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="Salary">
<%--http://www.codeproject.com/Articles/23471/Editable-GridView-in-ASP-NET--%>
<ItemTemplate >
<div >
<asp:TextBox Width="100px" OnTextChanged="tbSalary_TextChanged" AutoPostBack="True" style="text-align: right" TextMode="SingleLine" runat="server" ID="tbSalary" Text='<%# Bind("Salary", "{0:c0}") %>'></asp:TextBox>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want two columns - label (name) and textBox (salary). When user edits TextBox - data have to be updated automatically.
My CodeBehind looks like:
private static readonly DbManager DbManager = new DbManager();
private int selectedJobId = 1; // TODO:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlJobs.DataTextField = "name";
ddlJobs.DataValueField = "id";
ddlJobs.DataSource = DbManager.GetJobs();
ddlJobs.SelectedValue = selectedJobId.ToString();
ddlJobs.DataBind();
ddlJobs.DataBound += (o, args) =>
{
selectedJobId = Convert.ToInt32(ddlJobs.SelectedValue);
FillTable();
};
}
else
{
selectedJobId = Convert.ToInt32(ddlJobs.SelectedValue);
}
Page.DataBind();
}
protected void FillTable()
{
gridEmployees.DataSource = GetEmployees(); // List<Employees>
gridEmployees.DataBind();
}
I thought that row will raise Updated event when I update TextBox, but, unfortunately, it doesnt, probaly it's 'cause grid is not in editMode. So, I just made workaround - if TB edited - raise event and process it.
Well, now page is reloading with IsPostback = false, but no event is raised, not WebGrid's not TB's.
I've found some clue here, but my source is not SqlDataSource. What's wrong with my code, source? How to update row when TB changed in my case.
Just go through this artical .You will be able to fire textchange event from textbox inside the gridview
[http://www.codeproject.com/Tips/663684/Fire-TextBox-TextChanged-Event-from-GridView][1]
I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}