Inject record into DataList - asp.net

I would like suggestions on how to inject a record into my DataList to give an "All" option. Here is my code, data coming from the Northwind database.
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow" ShowFooter="False" ShowHeader="False"
RepeatDirection="Horizontal"
onitemcommand="DataList1_ItemCommand">
<ItemStyle CssClass="datalist" />
<ItemTemplate>
<%#(((DataListItem)Container).ItemIndex+1).ToString() %>
<asp:LinkButton ID="lbtnRegion" runat="server"
Text='<%# Eval("RegionDescription").ToString().Trim() %>'
CommandName='<%# DataBinder.Eval(Container.DataItem,"RegionID")%>' />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [RegionID], [RegionDescription] FROM [Region]"
ondatabinding="SqlDataSource1_Databinding"
onselected="SqlDataSource1_Selected">
</asp:SqlDataSource>
I am using the Link button in the Datalist to filter the territories and display them in a GridView.
What I would like to do is at some in the databinding process, add an Item in the DataList that will act as the ALL option, any suggestions would be appreciated.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
LinkButton lbtn;
foreach (DataListItem dli in DataList1.Items)
{
lbtn = (LinkButton)dli.FindControl("lbtnRegion");
if (lbtn != null)
lbtn.ForeColor = System.Drawing.Color.White;
}
string command = e.CommandName;
lbtn = (LinkButton)e.Item.FindControl("lbtnRegion");
if (lbtn != null)
lbtn.ForeColor = System.Drawing.Color.YellowGreen;
DataView dv = GetData(ref command); // Pass the RegionId
gvTerritory.DataSource = dv;
gvTerritory.DataBind();
}
Thanks

One way is to UNION ALL a 'All' value to the query fetching the list of drop down items.
SELECT 'All', 'All Regions'
UNION ALL
SELECT [RegionID], [RegionDescription] FROM [Region]
But if you have a lot of lists (or dropdowns) like this, it is better practice to create a custom control that injects an 'All' record for you.

It worked with the following SQL:
SELECT '-1' AS 'RegionID', 'All Regions' AS 'RegionDescription'
UNION ALL SELECT [RegionID], [RegionDescription] FROM [Region]

Used this on a drop down, may work the same on a datalist
Protected Sub ddlDataSources_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDataSources.DataBound
ddlDataSources.Items.Insert(0, New ListItem("All Data Sources", 0))
End Sub

Related

Gridview Dropdownlist binding

I am having a lot of trouble getting a dropdown to bind with data from my database with the appropriate departments.
This is what I have so far:
HTML:
<asp:GridView ID="gridDepartmentHistory" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Visible="true" Text='<%# Eval("Department")%>'></asp:Label>
<asp:DropDownList ID="ddlDepartment" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Start Date" HeaderText="Start Date" />
<asp:BoundField DataField="End Date" HeaderText="End Date" />
</Columns>
</asp:GridView>
Code behind:
Protected Sub gridDepartmentHistory_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gridDepartmentHistory.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ddlDepartment As DropDownList = CType(e.Row.FindControl("ddlDepartment"), DropDownList)
Dim list As ICollection(Of Department) = Department.hrGetDepartmentList() 'Class method to fill a collection of items with the Department's Name and ID
ddlDepartment.DataSource = list
ddlDepartment.DataTextField = "Name"
ddlDepartment.DataValueField = "ID"
ddlDepartment.DataBind()
Dim dept As String = CType(e.Row.FindControl("lblDepartment"), Label).Text
ddlDepartment.Items.FindByText(dept).Selected = True
End If
End Sub
When I run this it throws an exception saying:
Object reference not set to an instance of an object.
BTW: I am using this tutorial to help me through: http://www.aspsnippets.com/Articles/How-to-populate-DropDownList-in-GridView-in-ASPNet.aspx
Any help would be greatly appreciated! Thank you!
You simply need to retrieve dept id and store it in gridview as hidden (if you don't want to display it).
Dim dept As String = CType(e.Row.FindControl("lblDepartmentId"), Label).Text
ddlDepartment.SelectedValue = dept;
Hope it helps.
Your problem is that you ara trying to find the contorl in the row but is inside a table cell.
Try this.
Dim cbo As DropDownList = CType(YourDGV.Rows(x).Cells(0).FindControl("ddlDepartment"), DropDownList)

How to populate DropDownList in GridView EditItemTemplate depending on other column values

When editing a row in a GridView, I need a DropDownList whose list of available values depends on other column(s) in the row (let's just say the "type" of the record for now); that is, different options will be listed depending on which row is being edited.
I got it working after a fashion by adding an otherwise-unneeded DataKeyName to the GridView, but this is causing me grief elsewhere and anyway it feels too circuitous, so I'm looking for a better way. Here's how I'm currently doing it:
In .aspx file:
<asp:GridView ID="gvDct" ... DataKeyNames="dctId,dctType" ... >
...
<asp:TemplateField>
...
<EditItemTemplate>
<asp:DropDownList ID="ddlDctParent" runat="server"
DataSourceId="sdsDctParent"
DataValueField="dctId" DataTextField="dctFullPath"
SelectedValue='<%# Bind("dctParentId") %>'
... >
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDctParent" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
OnSelecting="sdsDctParent_Selecting"
SelectCommand="SELECT dctId, dctFullPath FROM lkpDocCatAndType
WHERE dctType=#dctType">
<SelectParameters>
<asp:Parameter Name="dctType" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
...
</asp:GridView>
I wanted the SelectParameter to be a ControlParameter with ControlID="gvDct" and PropertyName="SelectedDataKey.Values[dctType]", but for unknown reasons that didn't work (the parameter values were null), so I added this bit to the .vb code-behind file to populate the row-specific parameter for the data source of the DropDownList:
Protected Sub sdsDctParent_Selecting(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
e.Command.Parameters(0).Value = gvDct.DataKeys(gvDct.EditIndex).Item(1)
End Sub
So, when I start editing a row in the GridView, the DropDownList is bound, which causes the SqlDataSource SelectCommand to execute, which fires the OnSelecting code where I provide the parameter value from the row being edited (EditIndex) so that I get the appropriate population of values in the DropDownList.
Is there a "better" way? The most important aspect for me is to avoid adding the DataKeyName, because that is causing me a too-many-parameters problem on the stored procedure I'm using to delete a row from the GridView.
You should use Gridview RowDataBound where you can fetch the valueID a later on you can populate your Dropdownlist also add a label/hidden field whose value you want to populate DropdownList
Sry for writing code in c#.
You can try something like this
protected void gvDct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblValue = (Label)e.Row.FindControl("YourLableID")
DropDownList ddList= (DropDownList)e.Row.FindControl("ddlDctParent");
//bind dropdownlist
DataTable dt = con.GetData("Select Query where YourColumn='"+lblValue.text+"'");
ddList.DataSource = dt;
ddList.DataTextField = "dctFullPath";
ddList.DataValueField = "dctId";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddList.SelectedValue = dr["dctId"].ToString();
}
}
}

Dropdownlists with parent-child relation in EditItemTemplate Gridview not working

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.

Accessing Controls Inside ASP.NET View Controls (Event Handling)

If I have the following ListView, how can I attach a SelectedIndexChanged event listener to the DropDownList so I can perform a command on the respective object? Imagine I have a list of new users and I want to add them to a usergroup by selecting the group from the DropDownList.
<asp:ListView ID="NewUsers" runat="server" DataSourceID="NewUsersSDS" DataKeyNames="ID">
<LayoutTemplate>
<asp:Table ID="groupPlaceholder" runat="server"><asp:TableRow></asp:TableRow></asp:Table>
</LayoutTemplate>
<GroupTemplate>
<asp:TableCell ID="itemPlaceholder" runat="server"></asp:TableCell>
</GroupTemplate>
<ItemTemplate>
<asp:Table ID="NewUsersTable" runat="server" Width="32%" CssClass="inlineTable">
<asp:TableRow>
<asp:TableCell Width="100px"><%# Eval("FullName").ToString.Trim()%></asp:TableCell>
<asp:TableCell>
<asp:HiddenField ID="RowIndex" runat="server" Value="<%# Container.DisplayIndex %>" />
<asp:DropDownList ID="UserGroupSelect" runat="server" DataSourceID="UserGroupSelectSDS" DataValueField="ID" DataTextField="UserGroup"
OnSelectedIndexChanged="UserGroupSelect_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ItemTemplate>
</asp:ListView>
I've been having issues accessing controls inside of __View controls. I read in a few places that you could access them by NewUsers.FindControl([ControlID as String]) but this doesn't seem to be working for me. I guess this is what's called a dynamic control? Not really sure, feeling a bit lost.
As always, your help is greatly appreciated. ;)
Additional Info / Code
'Now working code, thanks to James :)
Protected Sub ItemBind(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles NewUsers.ItemDataBound
Dim lv As ListView = DirectCast(sender, ListView)
If e.Item.ItemType = ListViewItemType.DataItem Then
lv.DataKeys(e.Item.DataItemIndex).Value.ToString() 'get the datakey
End If
End Sub
Protected Sub UserGroupSelect_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim RowIndex As Integer = CInt(DirectCast(DirectCast(sender, DropDownList).Parent.FindControl("RowIndex"), HiddenField).Value)
Dim pk As Integer = CInt(NewUsers.DataKeys(RowIndex)("ID"))
Try
MessageBox("Update key " + pk.ToString, "Update Key") 'Custom js "alert" box function
Catch ex As Exception
MessageBox("Something went wrong, is the update key empty?")
End Try
End Sub
To access controls in a ListView (or any databound control), you need to use FindControl on the item/row:
ListViewItem item = ListView1.Items[0];
if (item != null)
{
DropDownList ddl = item.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
string value = ddl.SelectedValue;
}
}
As for attaching a SelectedIndexChanged event, you can do it like this:
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Container.DisplayIndex %>' />
</ItemTemplate>
Code-behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);
ListViewItem item = ListView1.Items[rowIndex];
if (item != null)
{
//your logic here
}
}
To retrieve a datakey:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);
int pk = (int)ListView1.DataKeys[rowIndex]["PrimaryKey"];
}

Dropdown list to filter gridview

I would like my gridview to be filtered by the dropdown list I have. It is pulling specific information from the database, so when you choose a value from the dropdown list, it should search through all the records and find only records with the ddl value in them.
The code that I am using in the codebehind for the SelectedIndexChanged is not right though. I get an error message saying 'Value' is not a member of 'Integer'. This is on the line dsCompanyFilter.SelectParameters.Add
It probably has something to do with the gridview not tying to the dropdown list properly, but I am not sure how to fix that code. Please help!
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server"><br /><br /><br />
<asp:linkbutton id="btnAll" runat="server" text="ALL" onclick="btnAll_Click" />
<asp:repeater id="rptLetters" runat="server" datasourceid="dsLetters">
<headertemplate>
|
</headertemplate>
<itemtemplate>
<asp:linkbutton id="btnLetter" runat="server" onclick="btnLetter_Click"
text='<%#Eval("Letter")%>' />
</itemtemplate>
<separatortemplate>
|
</separatortemplate>
</asp:repeater>
<asp:sqldatasource id="dsLetters" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT DISTINCT LEFT(ProductName, 1) AS [Letter] FROM [Product]">
</asp:sqldatasource>
Filter By Company:<asp:DropDownList ID="ddlCompany" runat="server"
DataSourceID="dsCompanyFilter" DataTextField="CompanyName" DataValueField="CompanyID">
</asp:DropDownList>
<asp:gridview id="gvProducts" runat="server" AutoGenerateColumns="False"
datakeynames="ProductID" datasourceid="dsProductLookup"
style="margin-top: 12px;">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="dsProductLookup" runat="server" connectionstring="<%$
ConnectionStrings:ProductsConnectionString %>"
Selectcommand="SELECT ProductID, ProductName FROM [Product] ORDER BY [ProductName]">
</asp:sqldatasource>
<asp:SqlDataSource ID="dsCompanyFilter" runat="server"
ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>"
SelectCommand="SELECT [CompanyName], [CompanyID] FROM [Company]">
</asp:SqlDataSource>
</asp:Content>
This code filters the results in the gridview by Letter and the Dropdown. The problem is with the dropdown list filtering the gridview.
Protected Sub btnLetter_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnLetter As LinkButton = TryCast(sender, LinkButton)
If btnLetter Is Nothing Then
Return
End If
dsProductLookup.SelectCommand = [String].Format("SELECT ProductID, ProductName
FROM [Product]
WHERE ([ProductName] LIKE '{0}%')
ORDER BY [ProductName]", btnLetter.Text)
End Sub
This is the part that has the problem. I now get the error, must declare the scalar variable #CompanyID
Protected Sub ddlCompany_SelectedIndexChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles ddlCompany.SelectedIndexChanged
dsProductLookup.SelectCommand = "SELECT ProductName, CompanyID, CompanyName
FROM Product, Company
WHERE CompanyID = #CompanyID
ORDER BY ProductName"
dsProductLookup.SelectParameters.Add("#CompanyID", DbType.Int32,
ddlCompany.SelectedValue)
End Sub
Deleted my previous answer.
Actually try the following :
dsProductLookup.SelectParameters.Add("#ProductID",
DbType.Int32, ddlCompany.SelectedValue)
No assignment to value as it is part of the Add. Noticed this when I tried to compile a test of my previous answer which didn't work.
EDIT: I tried the above code and it worked (did it in C#) but changed it to use DbType.Int32 for second param.
dsProductLookup.SelectParameters.Add("#ProductID", SqlDbType.Int).Value
It looks to me ilke the .Add() method is returning an int, to which .Value is not a property.
Confirmed it to make sure:
This is from the MSDN: Should help.
http://msdn.microsoft.com/en-us/library/w1kdt8w2.aspx
I'm guessing here -- I don't use SqlDataSources -- but it looks like SelectParameters.Add takes three parameters. What happens when change this:
dsProductLookup.SelectParameters.Add("#ProductID", SqlDbType.Int).Value = ddlCompany.SelectedValue
to this:
dsProductLookup.SelectParameters.Add("#ProductID", DbType.Int32, ddlCompany.SelectedValue)
or this:
dsProductLookup.SelectParameters.Add("#ProductID", TypeCode.Int32, ddlCompany.SelectedValue)

Resources