I'm trying to get an ASP.NET 3.5 GridView to show a selected value as string when being displayed, and to show a DropDownList to allow me to pick a value from a given list of options when being edited. Seems simple enough?
My gridview looks like this (simplified):
<asp:GridView ID="grvSecondaryLocations" runat="server"
DataKeyNames="ID" OnInit="grvSecondaryLocations_Init"
OnRowCommand="grvSecondaryLocations_RowCommand"
OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
OnRowDeleting="grvSecondaryLocations_RowDeleting"
OnRowEditing="grvSecondaryLocations_RowEditing"
OnRowUpdating="grvSecondaryLocations_RowUpdating" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPbxTypeCaption" runat="server"
Text='<%# Eval("PBXTypeCaptionValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS" runat="server"
Width="200px"
DataTextField="CaptionValue"
DataValueField="OID" />
</EditItemTemplate>
</asp:TemplateField>
</asp:GridView>
The grid gets displayed OK when not in editing mode - the selected PBX type shows its value in the asp:Label control. No surprise there.
I load the list of values for the DropDownList into a local member called _pbxTypes in the OnLoad event of the form. I verified this - it works, the values are there.
Now my challenge is: when the grid goes into editing mode for a particular row, I need to bind the list of PBX's stored in _pbxTypes.
Simple enough, I thought - just grab the drop down list object in the RowEditing event and attach the list:
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];
DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
Trouble is - I never get anything back from the FindControl call - seems like the ddlPBXTypeNS doesn't exist (or can't be found).
What am I missing?? Must be something really stupid.... but so far, all my Googling, reading up on GridView controls, and asking buddies hasn't helped.
Who can spot the missing link? ;-)
Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.
I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// This stmt is used to execute the code only in case of edit
if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
{
((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
}
}
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
You can use SelectedValue:
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS"
runat="server"
Width="200px"
DataSourceID="YDS"
DataTextField="CaptionValue"
DataValueField="OID"
SelectedValue='<%# Bind("YourForeignKey") %>' />
<asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
<asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:TemplateField HeaderText="SerialNo">
<ItemTemplate>
<%# Container .DataItemIndex+1 %>. 
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo">
<ItemTemplate>
<%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
<asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SName">
<ItemTemplate>
<%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
<asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cpp">
<ItemTemplate>
<%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
<asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Java">
<ItemTemplate>
<%-- <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
<asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<table>
<tr>
<td>
<asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
<asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
<asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
<asp:TextBox ID="txtc" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
<asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
<asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
</td>
</tr>
</table>
Related
I looked for some similar questions, but found only ListView solutions
But I have a GridView and a button outside of the GridView and need to udate only records specified by a selected checkbox.
<asp:GridView ID="gvData"
runat="server" Width = "850px"
CellPadding="5"
AutoGenerateColumns="false"
AllowPaging ="true"
OnPageIndexChanging ="OnPaging" PageSize="5">
<HeaderStyle CssClass="HeaderStyle" />
<PagerStyle CssClass="HeaderStyle" HorizontalAlign="Center" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<RowStyle CssClass="RowStyle" />
<RowStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="20px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblMessage" runat="server" Width="500px" Text='<%# Eval("Message") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="text-align:left;">
<asp:Button ID="btnChange" runat="server" Text="Change Type" OnClick="btnChange_Click" />
</div>
I have a method btnChange_Click():
protected void btnChange_Click()
{
int index = gvFailedMerchants.SelectedRow.RowIndex;
DbConnection.UpdateMessageType(index);
}
When I click the button, I'm getting the message
"Object reference not set to an instance of an object"
I want to write a logic that where I traverse the grid and add ids of the selected row into one string where all ids are separated by commas:
1,2,3,4,5
Then I will send this string to the stored procedure and use them in a query within IN close:
UPDATE MYTABLE SET column = myValue WHERE ID IN('1,2,3,4,5')
I do not know what is the right approach to the problem.
How can I do that?
Please try this,
<asp:TemplateField HeaderText="Select" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked = "false"
OnCheckedChanged="ChkSelect_CheckedChanged" data-id='<%# Eval("id") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
protected void ChkSelect_CheckedChanged(object sender, EventArgs e)
{
try
{
CheckBox chkSel = sender as CheckBox;
string id= chkSel.Attributes["data-id"].ToString();
if (chkSel.Checked == true)
{
Session["ID"] += (Session["ID"].ToString() == "" ? id: "," + id);
}
else
{
string existingCodes = Session["ID"].ToString();
Session["ID"] = existingCodes.Replace(id, "");
}
protected void btnChange_Click()
{
string ids = Session["ID"].ToString();
DbConnection.UpdateMessageType(ids);
}
This is My DataGrid:
<asp:DataGrid ID="dgAll" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>' ></asp:TextBox>
</ItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="drdL" runat="server" DataSource='<%#GetComboData(Eval("Value"))%>'></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
As you see I have a TextBox and a DropDownList, But I need just one of them in each row, So the question is how can I select ItemTemplate by condition, assume if Eval("Type") == "TextBox") I need TextBox and if Eval("Type") == "DropDown") I need DropDown in that Row. Does any one have any idea about this?
You can use both the controls in the same template field and use code as below
<asp:DataGrid ID="dgAll" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>'
Visible ='<%# Eval("Type").ToString()=="TextBox"%'>
</asp:TextBox>
<asp:DropDownList ID="drdL" runat="server"
DataSource='<%#GetComboData(Eval("Value"))%>'
Visible ='<%# Eval("Type").ToString()!="TextBox"%'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
why do you use couple asp:TemplateColumn, you can use too like that,
<asp:TemplateColumn>
<ItemTemplate>
<asp:TextBox ID="txtB" runat="server" Text='<%#Eval("Value")%>' Visible="false" ></asp:TextBox>
<asp:DropDownList ID="drdL" runat="server" Visible="false"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
and in the Grid's ItemDataBound event
protected void dgAll_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemIndex == -1) return;
if (e.Item.ItemIndex % 2 == 0)
e.Item.FindControl("drdL").Visible = true;
else
e.Item.FindControl("txtB").Visible = true;
}
I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="MatrĂcula" runat="server" Text="MatrĂcula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.
<asp:GridView ID="GridView1" runat="server"
style="height: 121px; width: 175px" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
onrowediting="GridView1_RowEditing" AutoGenerateColumns="false">
<Columns>
<asp:CommandField ButtonType="Button" SelectText="Edit" ShowEditButton="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Id") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCpuName" runat="server" Text='<%# Eval("cpuname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("cpuname") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("status") %>'>></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
SqlDataSource1.UpdateCommandType = SqlDataSourceCommandType.Text;
GridViewRow row = GridView1.Rows[e.NewEditIndex];
TextBox txt = (TextBox)row.FindControl("TextBox2");
SqlDataSource1.UpdateParameters["CpuName"].DefaultValue = txt.Text;
SqlDataSource1.UpdateParameters["cpuid"].DefaultValue = "3";
SqlDataSource1.Update();
BindGridView();
}
I am getting a object reference not set to an object on the textbox txt. I am not able to get the textbox2 in my gridview.
Can you try this
GridViewRow row = GridView1.Rows[GridView1.NewEditIndex];
TextBox txt = row.Cells[1].Controls[1] as TextBox;
If (txt!= null)
{
SqlDataSource1.UpdateParameters["CpuName"].DefaultValue = txt.Text;
SqlDataSource1.UpdateParameters["cpuid"].DefaultValue = "3";
SqlDataSource1.Update();
BindGridView();
}
Why you just don't get directly the textbox value? is this a great problem?
...
GridViewRow row = GridView1.Rows[e.NewEditIndex];
SqlDataSource1.UpdateParameters["CpuName"].DefaultValue = row.Columns["CpuName"].Value;
...
I don't know that this works, because I'm a C#-er, and basically work on winform not on web apps
First, here is the snippet from MSDN, RowEditing topic:
The RowEditing event is raised when a
row's Edit button is clicked, but
before the GridView control enters
edit mode. This enables you to provide
an event-handling method that performs
a custom routine, such as canceling
the edit operation, whenever this
event occurs.
To resolve the problem, handle the RowUpdating event for this purpose. There is an example which should be helpful to you at:
GridView.RowEditing event
Also, I believe you should use the Bind word to bind your TextBox to a field:
'>
For more details, please refer to the Data-Binding Expressions Overview
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.