Showing posts with label bound. Show all posts
Showing posts with label bound. Show all posts

Saturday, March 24, 2012

populate one dropdownlist based on the selected of another dropdownlist

hi
i am using c# asp.net
i have one datagrid in my form and i bound two dropdown list using coding. i loaded my database values in my first dropdown list by using this code:

private void Page_Load(object sender, System.EventArgs e)
{// Put user code to initialize the page here
if(!Page.IsPostBack)
{ BindData();
PopulateList();
}
}
public void BindData()
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT Course_NAME FROM JTSISControlManager_Course",conn);
DataSet ds = new DataSet();
ad.Fill(ds,"JTSISControlManager_Course");
DataGrid2.DataSource = ds;
DataGrid2.DataBind();

}
public DataSet PopulateList()
{

SqlDataAdapter ad = new
SqlDataAdapter("SELECT Course_Name FROM JTSISControlManager_Course", conn);

DataSet ds = new DataSet();
ad.Fill(ds,"JTSISControlManager_Course");
return ds;
}

here is the html coding:

<form id="Form1" method="post" runat="server">
<asp:datagrid id="DataGrid2" style="Z-INDEX: 101; LEFT: 328px; POSITION: absolute; TOP: 64px"
runat="server" Width="408px" AutoGenerateColumns="False" DataKeyField="Course_NAME">
<Columns>
<asp:BoundColumn DataField="Course_NAME" HeaderText="Course_NAME" />
<asp:TemplateColumn>
<HeaderTemplate>
<aspropDownList ID="Dropdownlist1" Runat="server" DataTextField="Course_NAME" OnSelectedIndexChanged ="DropDown_SelectedIndexChanged" DataSource =" <%#PopulateList()%> " AutoPostBack="True" />
<aspropDownList ID="Dropdownlist3" Runat="server" DataTextField="Dept_NAME" AutoPostBack="True" />
</HeaderTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid></form>

then using the following code i retreived my first dropdownlist value

protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
li=list.SelectedValue.Trim();
Response.Write(li);

}

my need is i want to use the retreived value of the first dropdownlist in query and fill the values in my second dropdownlist of the datagrid.
tell me how to use that retreived value of first dropdown list in next qurey and how to fill the second dropdownlist .so please help me to do this. give example coding to do my requirement
Edit/Delete MessageHi karthikeyan,

In my application I've Make and Model dropdowns. Model dropdown gets populated as soon as we select a make in a dropdown, it gets all the models for that make;

Here is my code;

Populating Model Dropdown
private void ddlMake_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ddlMake.SelectedValue != "")
{
PopulateFieldsInDropDowns("SELECT cat.DisplayText Model, to_char(cat.CATEGORYID) ModelID FROM TDCATEGORIES cat WHERE cat.CATEGORYLEVEL=4 and parentid= " + ddlMake.SelectedValue + " ORDER BY cat.DisplayText", ddlModel);
}
else
ddlModel.Items.Clear();
}

Populate Method
private void PopulateFieldsInDropDowns(string sqlQuery, DropDownList drpList)
{
try {
conn.Open();
OleDbCommand cmCommand = new OleDbCommand(sqlQuery, conn);
OleDbDataReader dreader = cmCommand.ExecuteReader();

drpList.Items.Clear();
drpList.Items.Add(new ListItem("", ""));

while (dreader.Read())
{
drpList.Items.Add(new ListItem(dreader.GetString(0), dreader.GetString(1)));
}

dreader.Close();

if (dreader != null)
dreader = null;

if (cmCommand != null)
cmCommand.Dispose();
}
catch
{
drpList.Items.Clear();
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Cannot Get Data: Cannot Get Required Data.";
}
conn.Close();
}

It should rock.

thanks,
hi ahmarshi,

i tried which u given, but i got error:
System.NullReferenceException: Object reference not set to an instance of an object.

my first dropdown name is DropDownList1 and second name is ddlmodel
i modified my coding like this:
protected void DropDown_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList list = (DropDownList)sender;
li=list.SelectedValue.Trim();
Response.Write(li);

if (li != "")
{
PopulateFieldsInDropDowns("SELECT Dept_NAME from JTSISControlManager_Department where Course_ID in (select Course_ID from JTSISControlManager_Course where Course_NAME= '" + li + "')", ddlmodel);
}
else
ddlmodel.Items.Clear();
}
private void PopulateFieldsInDropDowns(string sqlQuery, DropDownList drpList)
{
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
SqlDataReader dreader =cmd.ExecuteReader();


drpList.Items.Clear();
drpList.Items.Add(new ListItem("", ""));

while (dreader.Read())
{
drpList.Items.Add(new ListItem(dreader.GetString(0), dreader.GetString(1)));
}

dreader.Close();

if (dreader != null)
dreader = null;

if (cmd!= null)
cmd.Dispose();
}
catch
{
drpList.Items.Clear();
//lblMessage.ForeColor = System.Drawing.Color.Red;
Response.Write ( "Cannot Get Data: Cannot Get Required Data.");
}
conn.Close();
}

i kept break point and run this but while comming to
this line
private void PopulateFieldsInDropDowns(string sqlQuery, System.Web.UI.WebControls.DropDownList drpList)
in the drplist comes <undefined value>.
then after comming to this line
drpList.Items.Add(new ListItem("", ""));
it automatically goes to catch.please tell me and give sugestion to rectify this prooblem.

Wednesday, March 21, 2012

Populating a datagrid bound list view by a query

Hi,
My question today is below is my code which binds a listview to a databound column in my datagrid, but at the moment the list items are hard coded in. What I actually want is for the listitems to be populated from a lookup style query so possible from a data reader bringing back the ID which will be stored in the bound column but so the user just sees the Text associated with the value. Hope that makes sense.

<asp:TemplateColumn HeaderText="Model">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.FK_StockModelID") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropModel" Runat="server">
<asp:ListItem Value="1" text="1"></asp:ListItem>
<asp:ListItem Value="2" text="2"></asp:ListItem>
<asp:ListItem Value="3" text="3"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="DropModel" text="*" Runat="server" />
</EditItemTemplate>
</asp:TemplateColumn>

I think I can pretty much suss this out if I can work out how to access the dropdown list from tthe codebehind. So if anyone knows that as a starting point, please enlighten me.

PS sorry about the smilies in the code the ASP syntax just happent to be the same code.http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/creatingcustomcolumns.asp
Ok I found this code at the above link but Im struggling to use it, can anyone explain it line by line or tell me how to make it reference my template item shown above.
Private Sub dgNewCarriageBuildSheets_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgNewCarriageBuildSheets.ItemDataBound
If e.Item.ItemType = ListItemType.EditItem Then
Dim DRV As DataRowView = CType(e.Item.DataItem, DataRowView)
Dim Cu As String = DRV("ShipVia")
Dim DDL As DropDownList = CType(e.Item.Cells(4).Controls(1), DropDownList)()
Dim SQL As String = _
"SELECT ShipperID, CompanyName FROM Shippers ORDER BY ShipperID"
Dim DA As SqlDataAdapter = New SqlDataAdapter(SQL, ConnStr)
Dim DS As New DataSet
Dim item As ListItem
DA.Fill(DS, "Shippers")
DDL.DataSource = DS.Tables("Shippers").DefaultView
DDL.DataTextField = "CompanyName"
DDL.DataValueField = "ShipperID"
DDL.DataBind()
item = DDL.Items.FindByValue(CurrentShip)
If Not item Is Nothing Then item.Selected = True
End If
End Sub
Yes, you'd do it in the ItemDataBound event. After checking for the ItemType, declare a variable of type Combobox. Set it to e.Item.Cells(x).FindControl(your combobox id), and set the value of that combobox to the value you want from the dataset. You can use e.Item.ItemIndex to get the row number in the repeater/grid/dataset.
Private Sub dgNewCarriageBuildSheets_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgNewCarriageBuildSheets.ItemDataBound
If e.Item.ItemType = ListItemType.EditItem Then
Dim cboModel As DropDownList
Dim cboModel As DropDownList = e.Item.Cells(FindControl(DropModel))
'Also I have put DopModel as the ID of the Dropdown list in the item template but it doesnt seem to be recognised? Name DropModel is not declared

End If
End Sub
Fixed

Dim cboModel As DropDownList = e.Item.Cells(11).FindControl("DropModel")

Now to try the next bit...
Nearly there, I am now just getting an error at run time on the line underlined saying cannot convert dbnull to string?
Private Sub dgNewCarriageBuildSheets_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgNewCarriageBuildSheets.ItemDataBound
If e.Item.ItemType = ListItemType.EditItem Then
Dim lstItem As ListItem
Dim DRV As DataRowView = CType(e.Item.DataItem, DataRowView)
Dim CurrentModel As String = DRV("FK_StockModelID")
Dim cboModel As DropDownList = e.Item.Cells(11).FindControl("DropModel")
Main.objCarriageBuildSheet.GetStockModels() 'Populates a dataset
cboModel.DataSource = Main.objCarriageBuildSheet.dds_StockModels.dt_StockModels
cboModel.DataTextField = "Model"
cboModel.DataValueField = "FK_StockModelID"
cboModel.DataBind()
lstItem = cboModel.Items.FindByValue(CurrentModel)
If Not lstItem Is Nothing Then lstItem.Selected = True
End If
End Sub
DataBinder.Eval(e.Item.DataItem, "FK_StockModelID")
Like this ?
If e.Item.ItemType = ListItemType.EditItem Then

Dim lstItem As ListItem
Dim DRV As DataRowView = CType(e.Item.DataItem, DataRowView)
Dim CurrentModel As String = DataBinder.Eval(e.Item.DataItem, "FK_StockModelID") 'DRV("FK_StockModelID")
Dim cboModel As DropDownList = e.Item.Cells(11).FindControl("DropModel")

Main.objCarriageBuildSheet.GetStockModels() 'Populates a dataset
cboModel.DataSource = Main.objCarriageBuildSheet.dds_StockModels.dt_StockModels
cboModel.DataTextField = "Model"
cboModel.DataValueField = "FK_StockModelID"
cboModel.DataBind()
lstItem = cboModel.Items.FindByValue(CurrentModel)

If Not lstItem Is Nothing Then lstItem.Selected = True

End If

I still get same error
Hmm... maybe before you call that line, you should check whether e.Item.DataItem evaluates to null... place a breakpoint there and have a look at it.
It evaluates to a system.data.datarowview object
Hi Mendhak, I have finally solved the problem a different way.

My HTML code looks like this now, the main difference is I have set the datasource to a function in my code behind page.
<asp:TemplateColumn HeaderText="Model">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.FK_StockModelID") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id=DropModel Runat="server" DataValueField="ModelID" DataTextField="BrandModel" DataSource="<%# PopulateList %>" >
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" Runat="server" text="*" ControlToValidate="DropModel"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateColumn>

The function simply returns a previously filled dataset.
Public Function PopulateList() As DataSet

Return Main.objCarriageBuildSheet.dds_StockModels
End Function

this seems to be working nicely.

Friday, March 16, 2012

Populating Drop Down List

Hi,

I have a drop down list which is bound to a database field and is populated from so. However I want to add 1 of my own items to the drop down list no matter what is in the database. Is this possible?

ThanksYes. You can use the .Items.Add or .Items.Insert to add items to the dropdownlist. Just be sure to do this after you bind your data, because the bind will remove all items from the list.

hope this helps,
sivilian
Thanks very much, solved my problem.
Well the method is working but how we can set the additional item at the top, for example set "Select one State" on top of my drop down.

Thanks
Hello, try that in the page_load:

ddl.Items.Insert(new ListItem("text",value"),0);

regards
Thanks for you time,

Overload resolution failed because no accessible 'Insert' can be called with these arguments:

the aforsaid error return on line

AltShippingAdd.Items.Insert(new ListItem("Carbon", "C"),0);

Thanks in Advance
Hello,

this working fine, i think there is some problem in syntex.

AltShippingAdd.Items.Insert(0, New ListItem("Select One"))

the above statement is working fine but we can't able to define the value of that item is there a way to define the value of this item.

Thanks.
oh! in advance.
Hello, maybe you are right, I messed up with the syntax. but try to have:

AltShippingAdd.Items.Inert(0,new ListItem("Select One","1"))

regards
Thanks Bilal
It works fine
I am glad I was able to help you out my friend. For any further help, please dont hesitate to contact me here at the forums.

regards