ASP.Net: drop down list and data source created dynamically - asp.net

I have about 10 drop down list controls that get populated. Instead of copying/pasting and modifying a few fields on each, I would like to create them programmatically. Can this be done?
Here is what one of them looks like. I would like to programmatically add 10 dropdownlist controls and their respective SqlDataSource controls.
<asp:SqlDataSource ID = "ddlDAGender" runat=server
ConnectionString="<%$ ConnectionStrings:test1ConnectionString %>"
SelectCommand = "select GenderID,Gender from mylookupGender"
>
</asp:SqlDataSource>
<asp:Label ID="Label3" runat="server" Text="Gender"></asp:Label>
<asp:DropDownList ID="ddlGender" runat="server"
DataSourceid="ddlDAGender"
DataTextField="Gender" DataValueField="GenderID"
>
</asp:DropDownList>

You can always create your controls dynamically. In this case though, if all your drop down lists are different, I'm not sure it's saving you anything, since you'll still have to assign them individual ID's and datasources.
Here's what the code might look like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
}
protected void Page_Init(object sender, EventArgs e)
{
SqlDataSource sqlDS = new SqlDataSource();
sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
form1.Controls.Add(sqlDS);
DropDownList ddl = new DropDownList();
ddl.ID = "dddlGender";
ddl.DataSource = sqlDS;
ddl.DataTextField = "Gender";
ddl.DataValueField = "GenderID";
form1.Controls.Add(ddl);
// ... Repeat above code 9 times or put in a for loop if they're all the same...
}
private void BindDropDownLists()
{
foreach (Control ctl in form1.Controls)
{
if (ctl is DropDownList)
{
(ctl as DropDownList).DataBind();
}
}
}

Related

AspxGridView checkbox checked column value

I am using one aspxGridview where I used checkbox. Now I need when I check any of the row particular column value I should get in server side to complete my business logic.
Below is the gridview used:
<dx:ASPxGridView KeyFieldName="PracticeID" ID="ASPxGrd" runat="server" ClientInstanceName="grid"
ClientIDMode="AutoID" AutoGenerateColumns="false" Width="100%" OnSelectionChanged="ASPxGrd_SelectionChanged">
<Columns>
<dx:GridViewDataColumn VisibleIndex="0" Name="CheckBoxColumn">
<DataItemTemplate>
<dx:ASPxCheckBox ID="ASPxCheckBox1" runat="server" OnCheckedChanged="ASPxCheckBox1_CheckedChanged" AutoPostBack="true">
</dx:ASPxCheckBox>
</DataItemTemplate>
</dx:GridViewDataColumn>
<dx:GridViewDataColumn FieldName="PracticeName" Caption="Description" VisibleIndex="1">
<FooterTemplate>
Total:
</FooterTemplate>
</dx:GridViewDataColumn>
</dx:ASPxGridView>
I have tried to use oncheckedevent in checkbox with auto postback true and used code to get selected row like below:
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
but getting null value of grid object.
Need help.
In your example you have used DataItemTemplate, so in that case the sender will be the control which is added in that data template i.e ASPxCheckBox and you are casting it to grid bcoz of that it is getting null.
try out below snippet.
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxCheckBox checkBox = sender as ASPxCheckBox;
var grid = (checkBox.NamingContainer as DevExpress.Web.ASPxGridView.GridViewDataItemTemplateContainer).Grid;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
I found this answer before and it's working fine like below:
for (int i = 0; i < ASPxGrd.VisibleRowCount; i++)
{
ASPxCheckBox chk = ASPxGrd.FindRowCellTemplateControl(i, null, "ASPxCheckBox1") as ASPxCheckBox;
if (chk.Checked)
{
if (i == 0)
{
practiceName = ASPxGrd.GetRowValues(i, "PracticeName").ToString();
}
}
}
using this code i am able to get selected checkbox column value.

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.

problem with the nested gridview asp.net/C#

I have a gridview1 which is the parent gridview and I want to insert another gridview2 which is child gridview inside every row of parent gridview
This is the code in the .aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server">
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code that I have added inside the RowDataBound Event and i'm just binding the gridview2 with the arraylist which is filtered data depending upon the contents of each row's invoice number
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (GridViewRow gridviewrow in GridView1.Rows)
{
gridView2.AutoGenerateColumns = true;
String x = gridviewrow.Cells[1].Text;
softwareTitlesList = SoftwareListRetrieve();
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle);
}
gridView2.DataSource = titles;
gridView2.DataBind();
}
}
}
But nothing seems to be happening.
Please help me
Thanks in anticipation
One problem is that you are doing this inside the RowDataBound Event. This is going to be fired for every row in GridView1 that is bound to the datasource. You are essentially resetting the DataSource for GridView2 every time. Try using the DataBound Event of the gridview instead.
RowDataBound event fire when Rows bind the data. you have to do like...
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
gridView2.AutoGenerateColumns = true;
String x = dr["yourColumnName"].ToString();
softwareTitlesList = SoftwareListRetrieve();
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle);
}
GridView gridView2 = (GridView)e.Row.Findcontrol("gridView2");//add this
gridView2.DataSource = titles;
gridView2.DataBind();
}
}
Edit for comments:
GridView gridView2 = (GridView)e.Row.Findcontrol("gridView2");// add this line

Fill datagrid with paging enabled in asp.net

I have datagrid with paging enabled that can have 10 rows per page. Also I have DataTable with 16 rows. I want to fill the datagrid dynamically with 'for' loop to go over all the DataTable and fill the DataGrid.
I understand that there is a problem when the counter will hit row 11. Do I need to change the page of the datagrid when counter will be 11? Because it doesnt let me add more than 10 rows in the datagrid.
Would appriciate if someone can tell me how to implement it.
Thanks in advance,
Greg
This is pretty much how I'd do it. I'm not using a for as the conditional checking of checkboxes is in ItemDataBound, by doing it this way the DataGrid will do all the paging for me.
Markup:
<asp:DataGrid runat="server" ID="MyDataGrid" AllowPaging="true" PageSize="10" OnPageIndexChanged="MyDataGrid_PageIndexChanged" OnItemDataBound="MyDataGrid_ItemDataBound" Autogeneratecolumns="false">
<Columns>
<asp:BoundColumn DataField="Number" HeaderText="Number" />
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox runat="server" ID="CheckBox" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable numberDataTable;
if (!IsPostBack)
{
// Build a 16-row DataTable
numberDataTable = new DataTable();
numberDataTable.Columns.Add(new DataColumn("Number"));
for (int c = 1; c < 17; c++)
{
DataRow numberDataRow = numberDataTable.NewRow();
numberDataRow[0] = c;
numberDataTable.Rows.Add(numberDataRow);
}
ViewState.Add("Data", numberDataTable);
// DataBind the table into the DataGrid
MyDataGrid.DataSource = numberDataTable;
MyDataGrid.DataBind();
}
}
protected void MyDataGrid_PageIndexChanged(object sender, DataGridPageChangedEventArgs e)
{
DataTable numberDataTable;
// Get the DataTable out of Viewstate
numberDataTable = (DataTable)ViewState["Data"];
// Set the new page number
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
// Bind the grid
MyDataGrid.DataSource = numberDataTable;
MyDataGrid.DataBind();
}
protected void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
DataRow numberDataRow;
// Selective checking of the CheckBox
// Only do this for Item and ALternatingItem, we don't do this for headers, footers etc
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
numberDataRow = ((DataRowView)e.Item.DataItem).Row;
// Check if we have an even number
if ((int.Parse(numberDataRow[0].ToString()) % 2) == 0)
{
// Find our checkbox control in the DataGrid for the current row and check it
CheckBox checkBox = (CheckBox)e.Item.FindControl("CheckBox");
checkBox.Checked = true;
}
}
}
This gives:

How to extract extra data from LinqDataSource?

I have a simple wizard generated query in a LinqDataSource like this:
<asp:LinqDataSource ID="EvaluationsData" runat="server" ContextTypeName="Bonus.Models.BonusDataContext"
Select="new (Id, Name, Coverage)" TableName="BM_Evaluations"
</asp:LinqDataSource>
I assign this data source to a DropDownList, using Id and Name as the DataValueField and DataTextField respectively. But when I selected a option, I want to keep the Coverage too, extracting it from the data source and storage in a HiddenField. It's a way to do this without making another query to the database?
Thanks.
To do this, you'll need to intercept the returned list of items from the data source and then manually assign Coverage to the items in the drop-down's items.
Here's your markup
<asp:LinqDataSource ID="EvaluationsData" runat="server"
ContextTypeName="Bonus.Models.BonusDataContext"
Select="new (Id, Name, Coverage)" TableName="BM_Evaluations"
onselected="EvaluationsData_Selected">
</asp:LinqDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="EvaluationsData" DataValueField="Id" DataTextField="Name"
ondatabound="DropDownList1_DataBound">
</asp:DropDownList>
Here's your code
List<object> evaluations;
protected void EvaluationsData_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
evaluations = new List<object>(e.Result as IEnumerable<object>);
}
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in DropDownList1.Items)
{
var eval = evaluations.Where(a => a.Id == item.Value).FirstOrDefault();
if (eval != null)
{
item.Attributes.Add("Coverage", eval.Coverage);
}
}
}

Resources