related to this post Fill ComboBox Dynamically in asp.net.. help required I follow the code from that post, but when I tried to binding data, I've got error
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
<asp:TemplateField HeaderText="Step" SortExpression="ID"><InsertItemTemplate>
: <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource3" AutoPostBack="true"
DataTextField="Name" DataValueField="code" SelectedValue='<%# Bind("ID") %>' AppendDataBoundItems="true"
Width="300px" Height="25px">
<asp:ListItem Value=" " Text="---Select---"></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="KKL Step" SortExpression="ID">
<InsertItemTemplate>
: <asp:DropDownList ID="DropDownList6s" runat="server" DataSourceID="SqlDataSource5"
DataTextField="KKL_Name" DataValueField="ID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("ID") %>' Width="300px" Height="25px">
<asp:ListItem Value="" Text="---Select---"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:Koneksi %>"
SelectCommand="SELECT * FROM [TBL_KKL] WHERE (code=#code)">
<SelectParameters>
<asp:controlParameter controlID="DropDownList2"
propertyname="SelectedValue" Name="code" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</InsertItemTemplate>
</asp:TemplateField>
Its better to bind values to dropdown lists using C# code. Its ease and clear.
So in the RowDataBound event of the gridview you can write a code similar to this according to your syntax.
protected void dtgItemDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dtDetails = GetDetailsFromDataBase();
DropDownList DropDownList2= (DropDownList)e.Row.FindControl("DropDownList2");
DropDownList2.DataTextField = "Name";
DropDownList2.DataValueField = "ID";
DropDownList2.DataSource = dtDetails ;
DropDownList2.DataBind();
}
}
This is a sample code and you should change it according to yours.
Instead of DB calls inside the RowDataBound method, you can have Sessions or ViewStates with already filled with your data.
Related
I have two dropdown lists inside DetailsView, first dropdown DepartmentDropDown loads the data successfully from code behind using the following datasource
<asp:ObjectDataSource ID="dsDepartments" runat="server" SelectMethod="GetDepartments"
TypeName="MyCode.DepartmentEmployeeAssociations">
</asp:ObjectDataSource>
and the second dropdown EmployeeDropDown uses another datasource based on Department selection in the first dropdown (commented code works and loads the details view but not the control parameter code):
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<%--<asp:Parameter Name="deptId" Type="Int32" DefaultValue="7" />--%>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Here is the code in my GridView and DetailsView
<asp:Panel ID="AssociationView" runat="server" Visible="false">
<asp:GridView ID="gvAssociations" runat="server" AutoGenerateColumns="False" CssClass="GridViewStyle"
EmptyDataText="No rules defined" Width="100%" AllowPaging="True" GridLines="None"
DataKeyNames="Id" EnableModelValidation="True" DataSourceID="dsAssociations"
OnSelectedIndexChanged="gvAssociations_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="View" ItemStyle-Width="50px">
<ItemStyle Width="50px"></ItemStyle>
</asp:CommandField>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" Visible="False" />
<asp:BoundField DataField="Value1" HeaderText="Employee" SortExpression="Value1" Visible="false" />
<asp:BoundField DataField="Value1Description" HeaderText="Employee" NullDisplayText="*" />
<asp:BoundField DataField="Value2" HeaderText="Department" SortExpression="Value2" Visible="false" />
<asp:BoundField DataField="Value2Description" HeaderText="Department" NullDisplayText="*" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<div class="DetailsContainer">
<asp:DetailsView ID="dvAssociations" runat="server" Height="50px" GridLines="None"
CellPadding="5" AutoGenerateRows="False" DataKeyNames="sId" EnableModelValidation="True"
OnItemCreated="dvAssociations_ItemCreated" OnItemUpdating="dvAssociations_ItemUpdating"
OnItemInserting="dvAssociations_ItemInserting">
<Fields>
<asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="True" InsertVisible="False" Visible="false" />
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="false" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DepartmentDropDown" runat="server" SelectedValue='<%# Bind("Value2") %>'
DataSourceID="dsDepartments" DataValueField="DepartmentId" DataTextField="Name"
Enabled="true" AutoPostBack="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="false">
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server"
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" ShowDeleteButton="True" />
</Fields>
</asp:DetailsView>
</div>
</asp:Panel>
and the code behind:
protected void gvAssociations_SelectedIndexChanged(object sender, EventArgs e)
{
dvAssociations.PageIndex = gvAssociations.SelectedRow.DataItemIndex;
}
protected void dvAssociations_ItemCreated(object sender, EventArgs e)
{
if (dvAssociations.DataItem == null)
return;
// Some checks
}
protected void dvAssociations_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
//some code
}
protected void dvAssociations_ItemInserting(object sender, DetailsViewUpdateEventArgs e)
{
e.NewValues["Value1"] = ((DropDownList)((DetailsView)sender).FindControl("EmployeeDropDown")).SelectedValue;
}
public List<Department> GetDepartments()
{
// code to return List<Department> departments
// other code
return departments;
}
public List<Employee> GetAllEmployees(int deptId)
{
// code to return List<Employee> employees
// other code
return employees;
}
I tried various suggestions that were given in other SO articles, but still not able to make this work. My page don't load when I have the control parameter added, but it works if I change it to a normal parameter.
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
I am not sure what it doesn't like about it, it doesn't seem to bind the data in the details view. I added the AutoPostBack to true to the first dropdown and removed the SelectedValue='<%# Bind("Value1") %>' from the second dropdown as suggested in other posts, but nothing seems to be working.
Any help would be appreciated.
I have finally made it work, it was a silly mistake but again I haven't worked on these asp components before. So, there was some learning here and hope this will help someone having similar issue.
Firstly, make sure that your data in the GridView is correct and the dropdown column has valid value and is in the dropdown list source.
Secondly, I had to move my ObjectDataSource for employees with in the itemtemplate
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# Bind("Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName" Enabled="false">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="EmployeeDropDown" runat="server" SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>'
DataSourceID="dsEmployees" DataValueField="EmployeeId" DataTextField="FullName"
Enabled="true">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsEmployees" runat="server" SelectMethod="GetAllEmployees"
TypeName="MyCode.DepartmentEmployeeAssociations" DataObjectTypeName="Employee">
<SelectParameters>
<asp:ControlParameter ControlID="DepartmentDropDown" Name="deptId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</InsertItemTemplate>
</asp:TemplateField>
Also, I have replaced SelectedValue='<%# Bind("Value1") %>' to SelectedValue='<%# DataBinder.Eval (Container.DataItem, "Value1") %>' in my EmployeeDropDown aspx code to make it simpler. Which means, no need to add this event handler dvAssociations_ItemInserting to the DetailsView.
But, I have another issue related to orphan data in the grid, which doesn't exist in the dropdown - which make the ItemTemplate fail to load. That's for another post, this post is done for now. Hope it helps other.
Though this seems to be discussed before, I can't apply given help in my case:
I have 2 DropDownLists (DDL1, DDL2) inside the Edit Template of a Gridview, which is bound to a SQLDataSource. DDL2 depends on the selected value of DDL1. If I place the SQLDataSources that populate the DropDownLists on the top level, the ControlID of DDL2's ControlParameter isn't found even though I address it correctly (Gridview$DDL1ControlID). Therefore I placed the SQLDataSources inside the Edit Template of the Gridview. Now both DropDownLists are populated correctly if I enter in Edit Mode for a given Record; if I change the Index for DDL1, DDL2 is not updated automatically, as DDL2 has AutoPostBack set to false. Once I set AutoPostBack to true, the error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the " is thrown.
<asp:GridView runat="server" ID="Gridview1"
DataSourceID="Milestones"
DataKeyNames="ID"
OnRowEditing="OnRowEditing"
OnRowDataBound="OnRowDataBoundMS"
OnSelectedIndexChanged="OnSelectedIndexChangedMS">
....
<asp:templatefield HeaderText="Default Owner Group" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwnerGroup") %>' id="LabelDefaultOwnerGroup" Font-Size="12px" Width="50px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:SqlDataSource runat="server" id="OwnerGroups" ProviderName="System.Data.SqlClient"
ConnectionString="Data Source=XXXXX"
SelectCommand="select function, 2 as ord
from Staff
where function is not null
group by function
union all
select 'select' as function, 0 as ord
union all
select '-----' as function, 1 as ord
order by ord, function">
</asp:SqlDataSource>
<asp:DropDownList runat="server" id="DDOwnerGroup" Text='<%# Bind("DefaultOwnerGroup") %>' DataSourceID="OwnerGroups" DataTextField="function" DataValueField="function" Font-Size="12px" Width="80px" AutoPostBack="true"/>
</EditItemTemplate>
</asp:templatefield>
<asp:templatefield HeaderText="Default Owner" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwner") %>' id="LabelDefaultOwner" Font-Size="12px" Width="50px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:SqlDataSource runat="server" id="Owner" ProviderName="System.Data.SqlClient"
ConnectionString="Data Source=XXXXX"
SelectCommand="select Name, UserID
from Staff
where function = #OwnerGroup
union all
select Null as Name, Null as UserID
order by Name">
<SelectParameters>
<asp:ControlParameter ControlID="DDOwnerGroup" PropertyName="SelectedValue" Name="OwnerGroup" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList runat="server" id="DDOwner" Text='<%# Bind("DefaultOwner") %>' Width="100px" DataSourceID="Owner" DataTextField="Name" DataValueField="UserID" Font-Size="12px"/>
</EditItemTemplate>
</asp:templatefield>
I bind the DropdownLists in the OnRowDataBound Event like this:
<asp:templatefield HeaderText="Default Owner Group" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwnerGroup") %>' id="LabelDefaultOwnerGroup" Font-Size="12px" Width="50px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwnerGroup") %>' id="LabelDefaultOwnerGroupEdit" Visible="false"/>
<asp:SqlDataSource runat="server" id="OwnerGroups" ProviderName="System.Data.SqlClient"
ConnectionString="Data Source=XXXXX"
SelectCommand="...">
</asp:SqlDataSource>
<asp:DropDownList runat="server" id="DDOwnerGroup" DataSourceID="OwnerGroups" DataTextField="funcion" DataValueField="funcion" Font-Size="12px" Width="80px" AutoPostBack="true"/>
</EditItemTemplate>
</asp:templatefield>
<asp:templatefield HeaderText="Default Owner" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwner") %>' id="LabelDefaultOwner" Font-Size="12px" Width="50px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Text='<%# Bind("DefaultOwner") %>' id="LabelDefaultOwnerEdit" Visible="false"/>
<asp:SqlDataSource runat="server" id="Owner" ProviderName="System.Data.SqlClient"
ConnectionString="Data Source=XXXXX"
SelectCommand="...."
<SelectParameters>
<asp:ControlParameter ControlID="DDOwnerGroup" PropertyName="SelectedValue" Name="OwnerGroup" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList runat="server" id="DDOwner" Width="100px" DataSourceID="Owner" DataTextField="Name" DataValueField="UserID" Font-Size="12px"/>
</EditItemTemplate>
</asp:templatefield>
protected void OnRowDataBoundMS(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DDL1 = e.Row.FindControl("DDOwnerGroup") as DropDownList;
DropDownList DDL2 = e.Row.FindControl("DDOwner") as DropDownList;
Label LBL1 = e.Row.FindControl("LabelDefaultOwnerGroupEdit") as Label;
Label LBL2 = e.Row.FindControl("LabelDefaultOwnerEdit") as Label;
DDL1.SelectedValue = Convert.ToString(LBL1.Text);
DDL2.DataBind();
DDL2.SelectedValue = Convert.ToString(LBL2.Text);
}
}
}
I have this asp in a formview insert template.
<asp:FormView ID="FormViewReport" runat="server">
<InsertItemTemplate>
GAME_ID:
<asp:DropDownList ID="DropDownListReportIns" runat="server" AutoPostBack="true"
DataSourceID="SqlDataSourceGetGame"
DataTextField="GAME" DataValueField="ID" SelectedValue='<%# Bind("GAME_ID") %>' AppendDataBoundItems="True">
<asp:ListItem Text="ΠΑΡΑΚΑΛΩ ΕΠΙΛΕΞΤΕ ΑΓΩΝΑ" />
</asp:DropDownList>
HOME_PLAYER:
<asp:DropDownList ID="DropDownListRepo" runat="server"
DataSourceID="SqlDataSourceGetPlayers"
DataTextField="HOME_PLAYER_S" DataValueField="HP_ID" SelectedValue='<%# Bind("HOME_PLAYER_ID") %>' >
</asp:DropDownList>
The sql datasource of the second dropdownlist:
<asp:SqlDataSource ID="SqlDataSourceGetPlayers" runat="server" ConnectionString='<%$ ConnectionStrings:BasketballConnectionString1 %>' SelectCommand="SELECT HP.SURNAME blah blah blah WHERE (GAMES.ID = #GAME_ID)">
<SelectParameters>
<asp:ControlParameter ControlID="FormViewReport" PropertyName="SelectedValue" Name="GAME_ID"></asp:ControlParameter>
</SelectParameters>
In the second Dropdownlist the query needs the GAME_ID parameter and this is the DatavalueField of the first dropdownlist.How I can get the selected value from the first dropdownlist and give it to the second dropdownlist?
Put your SqlDatasource control inside the InsertItemTemplate of your FormView (with the DropDownLists), and then change it to this:
<asp:SqlDataSource ID="SqlDataSourceGetPlayers" runat="server" ConnectionString='<%$ ConnectionStrings:BasketballConnectionString1 %>' SelectCommand="SELECT HP.SURNAME blah blah blah WHERE (GAMES.ID = #GAME_ID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListReportIns" PropertyName="SelectedValue" Name="GAME_ID"></asp:ControlParameter>
</SelectParameters>
</asp:SqlDataSource
That way your ControlParameter is referencing the selected value of the 1st drop down.
Finally I did it using asp for the second dropdownlist:
<asp:DropDownList ID="DropDownListRepIns" runat="server" AppendDataBoundItems="True" EnableViewState="false"
DataSourceID="SqlDataSourceGetPlayers"
DataTextField="HOME_PLAYER_S" DataValueField="HP_ID" >
<asp:ListItem Text="ΠΑΡΑΚΑΛΩ ΕΠΙΛΕΞΤΕ ΑΓΩΝΑ" Value="0" />
</asp:DropDownList><br />
and a c# code for event item inserting that binds manually:
protected void FormViewReport_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["HOME_PLAYER_ID"] = ((DropDownList)((FormView)sender).FindControl("DropDownListRepIns")).SelectedValue;}
Also the solution this solution works without needing code behind:
SelectedValue='<%# DataBinder.Eval (Container.DataItem, "HOME_PLAYER_ID") %>'
You have to use this in the second dropdownlist in asp.
Using Visual Web Developer Express 2010 with ASP.NET 4.0.
I have a FormView and I want to set a default value from the database. I can't get it to bind to the value in the database. My FormView looks like this:
<asp:FormView
ID="frmOrderDetails"
DataSourceID="sdsFormOrderDetails"
runat="server"
DataKeyNames="orderId">
<EditItemTemplate>
<h3>Edit Order Details</h3>
<asp:Label ID="lblStrategy" Text="Strategy:" AssociatedControlID="ddlStrategies" runat="server" />
<asp:DropDownList SelectedValue='<%# Bind("strategyId") %>'
ID="ddlStrategies"
runat="server"
DataTextField="strategy"
DataValueField="strategyId"
DataSourceID="sdsStrategies"
/>
<asp:LinkButton
id="lnkUpdate"
Text="Update Order"
CommandName="Update"
Runat="server" />
|
<asp:LinkButton
id="lnkCancel"
Text="Cancel"
CommandName="Cancel"
Runat="server" />
</EditItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="sdsFormOrderDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetOrderDetails" SelectCommandType="StoredProcedure"
UpdateCommand="usp_UpdateOrder" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsStrategies" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetStrategiesDropDown">
</asp:SqlDataSource>
The EditItemTemplate does not even load when I click the edit button on my FormView control, but I don't get an error message either.
You need to do the following to bind a DropDownList to the EditItemTemplate:
Add the DropDownList and its DataSource to the EditItemTemplate.
Set the DropDownList parameters:
DataSourceID="SqlDataSourceDropDownlist" SelectedValue=<%# Bind("ValueToBind") %>
DataTextField="ValueToDisplay" DataValueField="ValueToBind"
Set the ListView / FormView DataSource <UdateParameters>: <asp:Parameter Name="RankID" Type="Int32" />
you need to use formview Databound event like
protected void frmOrderDetails_DataBound(object sender, EventArgs e)
{
if (frmOrderDetails.CurrentMode == FormViewMode.Edit)
{
DropDownList ddlStrategies = (DropDownList)frmOrderDetails.FindControl("ddlStrategies");
ddlStrategies.SelectedValue = Your DB Value Goes here;
}
}
I am trying to update a TextBox within currently edited row within a GridView on when changing items on a DropDownList and I cant quite get it going in VB. I found this code in c# but don't know if I'm on the right track?
Can you please offer some help?
PS: This code is for an OnMouseOver event but the point is to update the TextBox while in edit mode.
<ItemTemplate>
<asp:TextBox runat="server" ID="tx1" onmouseover='<%# "ChangeValue(" +((DataGridItem)Container).FindControl("tx1").ClientID + ")"%>'></asp:TextBox>
</ItemTemplate>
JS Code:
function ChangeValue(i)
{
var t=i.id
document.getElementById(t).value="Hello World!";
}
Try the following:
Put the following script in head tag:
<script language="javascript" type="text/javascript">
function ChangeValue(ddl,txtid)
{
var txt=document.getElementById(txtid);
var dval= ddl.options[ddl.selectedIndex].value;
if(dval=="1")
{
txt.value="It's 1";
}
if(dval=="2")
{
txt.value="It's 2";
}
if(dval=="3")
{
txt.value="It's 3";
}
}
</script>
Try the gridview below:
<asp:GridView ID="GridView1" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
AutoGenerateColumns="false" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand"
runat="server" OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:CommandField ButtonType="link" ShowEditButton="true" ShowCancelButton="true" />
<asp:TemplateField HeaderText="CategoryID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl" runat="server">
<asp:ListItem Text="1" Value="1" Selected="true"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComments" runat="server"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName">
<ItemTemplate>
<asp:LinkButton ID="lnkName" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Handle the rowcreated event in codebehind:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
TextBox txt = (TextBox)e.Row.FindControl("txtComments");
txt.Text = "It's 1";
//------------ Set onchange function for dropdown---------------------------//
ddl.Attributes.Add("onchange", "javascript:ChangeValue(this,'" + txt.ClientID + "');");
}
}
Bind the grid with Categories table in northwind db.