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.
I have a dropdownlist in my gridview. The datas in dropdownlist are "Y" and "N".These two letters. If I select Y then the cell value 6 will be need to become zero. But its not working. Here is my code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList DropDownList3=(DropDownList)e.Row.FindControl("DropDownList");
//if (DropDownList3 == null)
//if (DropDownList3.SelectedValue == "Y")
if(DropDownList3.SelectedItem.Text == "Y")
{
e.Row.Cells[6].Text = "0";
}
else
{
e.Row.Cells[6].Text = "1";
}
}
}
This is my dropdowlist template field
<asp:TemplateField HeaderText="Alt">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
First, You have to set AutoPostBack="true" for DropDownList3, and You have to create EventHandler for ddl, but in RowCreated not in RowDataBound.
There is example (it's vb.net) :
aspx:
<asp:TemplateField HeaderText="Alt">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="true">
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
and then, code behind :
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid1.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = CType(e.Row.FindControl("DropDownList3"), DropDownList)
AddHandler ddl.SelectedIndexChanged, AddressOf ddlChange
End If
End Sub
Private Sub ddlChange(ByVal sender As Object, ByVal e As EventArgs)
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim row As GridViewRow = ddl.NamingContainer
If ddl.SelectedItem.Text = "Y" Then
row.Cells(6).Text = "0"
Else
' do what You want
End If
End Sub
It's very important You don't bind Your GridView after every PostBack, and, of course, EnableViewState must be set to True.
Since I'm working in vb.net, I'll try to convert this code into c#.
Update :
There is c# code (I used online converter) :
private void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
if ((e.Row.RowType == DataControlRowType.DataRow)) {
DropDownList ddl = ((DropDownList)(e.Row.FindControl("DropDownList3")));
ddl.SelectedIndexChanged += new System.EventHandler(this.ddlChange);
}
}
private void ddlChange(object sender, EventArgs e) {
DropDownList ddl = ((DropDownList)(sender));
GridViewRow row = ddl.NamingContainer;
if ((ddl.SelectedItem.Text == "Y")) {
row.Cells[6].Text = "0";
} else {
// do what You want
}
}
Please do not down vote. i am new to this site.
i tried myself but repeatedly the same error occurring.
protected void gvDepPayment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("lblDeptName");
DataTable dT = (DataTable)ViewState["DataBounded"];
DataRow[] drows = dT.Select("DepartmentName = '" + lbl.Text + "'");
int Count = 0;
foreach (DataRow item in drows)
{
Count += Convert.ToInt32(item["PaidAmount"]);
}
Label lblPaidAmount = (Label)e.Row.FindControl("lblPaidAmount");
lblPaidAmount.Text = Count.ToString();
}
}
<asp:GridView ID="gvDepPayment" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvDepPayment_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Department Name">
<ItemTemplate>
<asp:Label ID="lblDeptName" runat="server" Text='<%#Eval("DepartmentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Collection">
<ItemTemplate>
<asp:Label ID="lblPaidAmount" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i want find the Payment list and show it in grid view like Department wise
This error message is caused by your reading the content of the DataRow at the column named PaidAmount, probably there are some null values in the set of rows returned by your query. In this scenario you could use the IsNull method of the DataRow class with the conditional operator. In the case of DBNull.Value you want to add zero to your count.
Count += item.IsNull("PaidAmount") ? 0 : Convert.ToInt32(item["PaidAmount"]);
I have a page with gridview in it.
My gridview shows the products Information and Admin can Edit gridviews columns.
Two of my columns show the brand name and category name for each product;
I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop)
in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop.
Brands name in my brand table in database are:
Samsung, Nokia,Sony Ericsson,Apple,LG,HTC....
and my categories name in category table are :
Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g,wt18i,w8,500,n8...
When I click the Edit button, first item in the branddrop is Equal to brandlable.
Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.text in ItemTemplate and the category drop does not show the related categories name to brandname.for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work. I dont know how to solve it.
this is my first code:
<asp:TemplateField HeaderText="brand name">
<ItemTemplate>
<asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
<asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%>
<asp:DropDownList ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true" OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="category name">
<ItemTemplate>
<asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="categoryDrop" runat="server" AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3"> <%-- --%>
</asp:DropDownList>
<asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=#idfrombrands " >
<SelectParameters>
<asp:ControlParameter ControlID="brandDrop"
Name="idfrombrands" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
this is my code behind for GridView1_RowDataBound and GridView1_RowUpdating:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int brand=0;
int category=0;
//Drop Brand--------------------------------------
DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");
if (list1.SelectedItem.Value != null)
{
brand = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand
}
else
{
brand = Convert.ToInt32(lbl.Text);
}
//Drop Category----------------------------------------
DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");
//int NewIdFromBrand2 = -1;
if (list2.SelectedItem.Value != null)
{
category = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2
}
else
{
category = Convert.ToInt32(lbl2.Text);
}
//Photo-------------------------------------------
string photoname = System.Guid.NewGuid().ToString();
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage");
if (fileUpload != null && fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);
SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
}
else
{
SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;
}
int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
DataTable tb = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateProduct";
cmd.Parameters.AddWithValue("#brandid", brand );
cmd.Parameters.AddWithValue("#catid", category );
cmd.Parameters.AddWithValue("#pid", prid);
try
{
cn.Open();
cmd.ExecuteNonQuery();
SqlDataSource1.DataBind();
}
catch (Exception ex2)
{
}
finally { cn.Close(); }
//GridView1.EditIndex = -1;
//GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
//Label1.Text = ddlStatus.SelectedValue;
}
}
}
}
}
Thank you so much Abide Masaraure.you helped me a lot.
I deleted grideview_rowediting and braddrop_selectedIndexChange event And just added two lines to my GridView1_RowDataBound event.
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
now my event is like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
}
}
}
}
}
Eureka!!!.You owe me a cup of coffee.I replicated your problem and realized after two hours that you need to actually hook to your index selected changed event.The trick is to use the naming container property to locate your drop downs,they think are pretty hidden ,but the sender argument enables us to expose them when dropband dropdown fires. And presto everything works like a charm.
Use this code snipet in your selected changed event.
protected void dropBand_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList dropBand = (DropDownList)sender;
SqlDataSource dsc = (SqlDataSource)dropBand.NamingContainer.FindControl("SqlDataSource3");
DropDownList categoryDrop = (DropDownList)dropBand.NamingContainer.FindControl("categoryDrop");
dsc.SelectParameters("BrandID").DefaultValue = dropBand.SelectedValue;
categoryDrop.DataBind();
}
I can send you a zip file of the demo this time if you happen to continue having issue.Happy Coding!!!.
I need to see your code you are using in your selected index changed event.
The following cascading drop down technique will take away all the suffering you have in trying to hook up the parent and its children...I use this wonderful feature in the Ajax control toolkit in all my projects.You can use any data retrieval method you want as long it returns an array.I am using linq in this example for data retrieval.
Assuming I have tables named Brand and Model and classes : Brand and Model and collections: Brands and Models
In 'YourWebServicePath.asmx' (Web service file)
<WebMethod()> _
Public Function GetBrands(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim result = From b As Bands In Brand.Brands Select New CascadingDropDownNameValue(b.BrandDesc, b.BrandID.ToString())
Return result.ToArray()
End Function
<WebMethod()> _
Public Function GetModels(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim brandID As Guid
Dim brandValues As StringDictionary = AjaxControlToolkit.CascadingDropDown._
ParseKnownCategoryValuesString(knownCategoryValues)
brandID = New Guid(brandValues("Brand"))
Dim result = From m As Models In Model.GetModels() Where m.brandID = brandID Select New CascadingDropDownNameValue(m.ModelDesc,
_ m.ModelID.ToString())
Return result.ToArray()
End Function
MarkUp
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<EditItemTemplate>
<asp:DropDownList ID="dropBrand" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="BrandCascadingDropDown"
runat="server"
Category="Brand"
TargetControlID="dropBrand"
PromptText="-Select Brand-"
LoadingText="Loading Brands.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetBrands">
</cc1:CascadingDropDown>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dropModel" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="ModelCascadingDropDown"
runat="server"
Category="Model"
TargetControlID="dropModel"
ParentControlID="dropBrand"
PromptText="-Select Model-"
LoadingText="Loading Models.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetModels" >
</cc1:CascadingDropDown>
And thats all you need.No need of wiring the events.And voila! let the toolkit perform the magic.
To use the above code i gave you in a row editing event you have to modify it like so.Then those objects won't be null.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView testgrid = (GridView)(sender);
testgrid.EditIndex = e.NewEditIndex;
testgrid.DataBind();
DropDownList dropBand = (DropDownList)testgrid.Rows[e.NewEditIndex].FindControl("ddlProducts");
//
}
Something is definitely happening in your page cycle and is keeping on biting you.I suggest zip an mdf of your database and the offending aspx page and let me tackle it from here if you don't get it to work.Never give up.
Below is my gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting">
<asp:TemplateField HeaderText="Amount" HeaderStyle-ForeColor="DimGray" >
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" HeaderStyle-ForeColor="DimGray" >
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
in the RowData_BoundEvent
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl2 = (Label)e.Row.FindControl("lblamount");
if(amount>0) {lbl2.Text = amount;} else lbl2.Text = string.Empty;
Label lbl3 = (Label)e.Row.FindControl("lblprice");
if(price>0) {lbl3.Text = price;} else lbl3.Text = string.Empty;
If there is no value entered either in Amount or Price , I am trying not to display the values in the gridview if the amount is not greater than zero. But still, the grid displays Amount as Label and Price as Label if the condition does not satisfy.
You should use the GridViewRow's DataItem to get these values.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the underlying data item. In this example
// the underlying data item is a DataRowView object.
DataRowView rowView = (DataRowView)e.Row.DataItem;
Double amount = (Double)(rowView["amount"]);
Double price = (Double)(rowView["price"]);
Label lblamount= (Label)e.Row.FindControl("lblamount");
Label lblprice = (Label)e.Row.FindControl("lblprice");
lblamount.Text = amount > 0 ? amount.ToString() : String.Empty;
lblprice.Text = price > 0 ? price.ToString() : String.Empty;
}
}