How Do I Bind Dropdown To Value Present In Database - c#

I am using datalist control an asp.net using C# and sqlserver 2008.I have a dropdown in datalist and need to display it's current value from database on page load.
I have tried this so far,
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
DropDownList ddlshowit = (DropDownList)e.Item.FindControl("DropDownList4");
ddlshowit.DataSource = ds;
ddlshowit.DataTextField = "showit";
ddlshowit.DataValueField = "showit"; //showit is my column name
ddlshowit.DataBind();
}
}
I also tried adding the following declaration in markup: SelectedValue='<%#Eval("showit")%>' but it also didn't work. Please Help

You can find your dropdownlist from your datalist in this way,
Protected void Page_load(object sender,Eventargs e)
{
foreach(DataList dl in DataList1.Items)
{
DropDownList ddlshowit = (DropDownList)dl.FindControl("DropDownList4");
}
}
Let me know the output.

Related

Gridview created duplicate rows

I have a Gridview that populate with an item from the listview is click.
However my Gridview will create duplicate rows upon trigger from list view item command.
My listview and gridview are on the same page.
Any solution to avoid that?
The following code is how i bind data to gridview from listview item_command method:
protected void loadDataEvent(string categoryid)
{
Module_Category mc = new Module_Category();
gvEventByCategory.DataSource = mc.Get_All_Event_By_Category(categoryid);
gvEventByCategory.DataBind();
}
protected void lkbtnCatItem_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Enter")
{
loadDataEvent(e.CommandArgument.ToString());
}
}

asp.net gridview paging issue when rebinding it for a search result

I have a grid view and I bind it on first page load , I have some searching optionst on the same page , when search button is clicked I query the seaarch and i rebind the gridview with the new datasource comming out of search result , the problem is after rebinding the gridview I have paging problems which I don't have them in the first pageload data binding ! could anyone tell me why is that ?!
Here is my Page_Load coe :
protected void Page_Load(object sender, EventArgs e)
{
DisableChaching();
string val = Convert.ToString(Session["AccessLevel"]);
if (Request.Cookies["UserName"] == null)
{
if (Session["UserName"] == null)
{
Response.Redirect("~/Default.aspx");
}
else if (val == "2")
{
Response.Redirect("~/Default.aspx");
}
}
else if (val == "2")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
LoadControls();
BindGrid();
}
}
My GV_PageIndexChanging :
protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GV.PageIndex = e.NewPageIndex;
BindGrid();
PageStatus(Status.None);
}
my btnSearch_Click :
protected void btnSearch_Click(object sender, ImageClickEventArgs e)
{
query = new CommonQueries();
GV.DataSource = query.getBooksByGroupIDSubGroupID(DrpGroup.SelectedItem.Value,DrpSubGroup.SelectedItem.Value);
GV.DataBind();
}
And in CommonQueries Class I have this query wich I used befor :
public List<Book> getBooksByGroupIDSubGroupID(string GroupID, string SubGroupID)
{
db = new BookMarketDataContext();
List<Book> list = new List<Book>();
list = (from b in db.Books where b.GroupID.ToString() == GroupID && b.SubGroupID.ToString() == SubGroupID orderby b.Name select b).ToList();
return list;
}
TO BE MORE SPECIFIC : On my Page loads I don't have any problem with gridview page changing
BUT after clicking the search button "btnSearch" and rebinding the gridview , if search results are enough to cause the gridview to have pagenumbers , and when I click one of those page numbers I get wrong results from the previous page_Load !
It appears that your postback on paging doesn't include information on which viewstate it should be paging. You should be pushing that information down to the page so that it can be included in the postback, or storing it in user session (less roundtrip, more weight on the server, but faster responses if you're also storing the query result)...

Trying to populate drop-down list in GridView edit

I have the following code trying to populate drop-down list when I click edit on a Grid View, and it gives me the following error:
" 'ddlgvRoom' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value"
Any idea on why I need to add code into the row editing event, and if so can you help? My gridview is getting its values from an objectdatasource.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList dl = (DropDownList)e.Row.FindControl("ddlgvRoom");
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlgvRoom = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlgvRoom");
string strgvRoom = ddlgvRoom.SelectedItem.Text.ToString();
DropDownList ddlgvJack = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlgvJack");
string strgvJack = ddlgvJack.SelectedItem.Text.ToString();
DropDownList ddlgvVlan = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlgvVlan");
string strgvVlan = ddlgvVlan.SelectedItem.Text.ToString();
GridView1.DataBind();
}
}
Had to take off the selectedvalue off the HTML side and everything started working

Dynamically adding Page size dropdown list in the Gridview Pager

I have a Gridview for which Dropdown list has to be added on the run time at the Pager row. I have added the below code on the Gridview RowCreated.
protected void gv_transaction_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
using (DropDownList ddlpagesize = new DropDownList())
{
ddlpagesize.Items.Add("25");
ddlpagesize.Items.Add("50");
ddlpagesize.Items.Add("75");
ddlpagesize.Items.Add("100");
ddlpagesize.Items.Add("150");
ddlpagesize.Items.Add("200");
ddlpagesize.AutoPostBack = true;
ddlpagesize.Items.FindByText(gv_transaction.PageSize.ToString()).Selected = true;
ddlpagesize.SelectedIndexChanged += ddlpagesize_SelectedIndexChanged;
using (Table tbl = (Table)e.Row.Cells[0].Controls[0])
{
using (TableCell cell = new TableCell())
{
cell.Controls.Add(new LiteralControl("<b>Page Size: </b>"));
cell.Controls.Add(ddlpagesize);
tbl.Rows[0].Cells.AddAt(0, cell);
}
}
}
}
}
protected void ddlpagesize_SelectedIndexChanged(object sender, EventArgs e)
{
using (DropDownList ddlpagesize = (DropDownList)sender)
{
gv_transaction.PageSize = int.Parse(ddlpagesize.SelectedValue);
gv_transaction.PageIndex = 0;
BindTransactionGrid();
}
}
Now, SelectedIndex change event is not firing, when I change the dropdownlist value.
But interestingly, when I remove the using statement from the initiation of page size Dropdownlist; Selectedindex event is firing perfectly. Please tell me if there is any relation with the disposing of dropdownlist and selectedIndex Changed event for the dynamic dropdown in a Gridview
You don't need to wrap asp.net controls in using statements, asp.net will call dispose automatically on your controls, i think your using statements are causing them to be disposed too early.

How to get the bound item from within an ASP.NET repeater

I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)

Categories