Dropdown in dataview - c#

In my GridView, I have the following columns:
<Columns>
<asp:BoundField DataField="report_type" HeaderText="Report Type"
SortExpression="report_type" />
<asp:BoundField DataField="progress" HeaderText="Progress"
SortExpression="progress" />
<asp:TemplateField HeaderText="..">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="progress">
<asp:ListItem Value="0">Incomplete</asp:ListItem>
<asp:ListItem Value="1">Complete</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
The progress column is just there for demo purposes which will eventually be removed. How do I get the value of the progress to select the correct itemlist in the dropdown?
So if the value of progress is 1, the dropdown should have Complete selected. If the value of the progress is 0, the dropdown should have Incomplete selected.

Add a OnRowDataBound attribute to the gridview in the .aspx page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" OnRowDataBound="GridViewRowEventHandler">
Replace
<asp:BoundField DataField="Progress" HeaderText="Progress"
SortExpression="progress" />
with
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="progress_Flags" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Progress").ToString()%>'/>
</ItemTemplate>
</asp:TemplateField>
In the code behind:
protected void GridViewRowEventHandler(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label flag = (Label)e.Row.FindControl("progress_Flags");
DropDownList myDropDown = (DropDownList)e.Row.FindControl("DropDownList1");
if (flag.Text == "1")
{
myDropDown.SelectedValue = "1";
}
//add more conditions here..
}
}

In RowDataBound event you can use e.Row.FindControl
protected void GridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
DataRowView dr = row.DataItem as DataRowView;
// now find the control in the row by control ID
DropDownList myDropDown = row.FindControl("DropDownList1") as DropDownList;
}

Related

Bind DropDownList in asp.net in Item Template on row databound

I am trying to bind a dropdown which is in a grid but I am getting error.
<asp:GridView ID="grdddl" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="grdddl_RowDataBound" ShowFooter="true" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlcommtype" SelectedValue='<%#Eval("ComPlanRoleDescr") %>' AutoPostBack="true" OnSelectedIndexChanged="ddlcommtype_SelectedIndexChanged" runat="server"></asp:DropDownList>
<asp:HiddenField ID="hdnid" Value='<%#Eval("ID") %>' runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlcommtypefooter" AutoPostBack="true" OnSelectedIndexChanged="ddlcommtypefooter_SelectedIndexChanged" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdddl_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtype");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtypefooter");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
}
}
This Code is giving error:
'ddlcommtype' has a SelectedValue which is invalid because it does not exist in the list of items.
In your GridView you are setting a SelectedValue for your DropDownList, but
the value cannot be found in the ListItem's that belong to the DropDownList.
Remove the SelectedValue from this line:
<asp:DropDownList ID="ddlcommtype" SelectedValue='<%#Eval("ComPlanRoleDescr") %>' AutoPostBack="true" OnSelectedIndexChanged="ddlcommtype_SelectedIndexChanged" runat="server"></asp:DropDownList>
If you do want to use a SelectedValue, why not do it after DataBind()? For example:
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtype");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
// Now set the default value:
ddlcommtype.SelectedValue = "InsertValueHere";

Can't bind checkboxes in Gridview

I have a GridView that displays a list and the user can select a checkbox for each item.
So for example I check the second row. I can see in the database that the check value next to this description has updated to 1:
But when I go back into the GridView, all the checkboxes are blank again.
Code for GridView:
<asp:GridView style="width:75%"
ID="gvCVRTDetails"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvCVRTDetails_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
AlternatingRowStyle-BackColor="#EEEEEE">
<HeaderStyle CssClass="tblResultsHeader" />
<Columns>
<asp:BoundField DataField="ChecklistID" HeaderText="ID" ></asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Checklist Items"></asp:BoundField>
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void gvCVRTDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lookupCVRT work = (lookupCVRT)e.Row.DataItem;
GridView gv = sender as GridView;
e.Row.Attributes.Add("ID", "gvCVRTDetails_" + work.ID);
e.Row.Cells[0].Attributes.Add("onclick", "event.stopPropagation();");
CheckBox chkChecked = e.Row.FindControl("chkChecked") as CheckBox;
if(work.Checked)
{
chkChecked.Checked = true;
}
}
}
I tried setting chkChecked.Checked = true; if there is a value for the Checked field in the database but that didn't work. How do I get the checkboxes to show as ticked if the value in the database is equal to 1?
Binding the Grid:
protected void gridviewParent_SelectedIndexChanged(object sender, EventArgs e)
{
List<lookupCVRT> workDetails = lookupCVRT.GetChecklistItemsByChecklistID(Company.Current.CompanyID, ParentID.ToString(), gvCVRT.SelectedDataKey.Value.ToString());
gvCVRTDetails.DataSource = workDetails;
gvCVRTDetails.DataBind();
FireJavascriptCallback("setArgAndPostBack ();");
}
You should bind the checkbox to the property that you read from db, something like:
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" Checked='<%# Bind("YourCheckPropertyFromModel") %>'runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>

How to bind 2 databse tables to gridview and one as dropdown

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="301px" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="StudentName" HeaderText="StudentName" SortExpression="StudentName" />
<%-- <asp:BoundField DataField="StudentDOB" HeaderText="StudentDOB" SortExpression="StudentDOB" />--%>
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/Employee/EmployeeEditPage.aspx?StudentID={0}", Eval("StudentID"))%>'> Edit</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
above is my design:
below I wrote my code for to display the database, which have table departmenttable and another table studenttable to show the values into the grid. in department table I have departmentname(dept_name)
which should come in dropdown inside the gridview..but it showing error..pls help..
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(DataBase.GetConnection());
con.Open();
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList = (DropDownList)e.Row.FindControl("dept_name");
//bind dropdownlist
DataTable dt = con.GetData("select dept_name from dbo.DepartmentTable");
ddList.DataSource = dt;
ddList.DataTextField = "dept_name";
ddList.DataValueField = "DeptName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["DeptName"].ToString();
con.Close();
GridView1.DataBind();
}
}
}
For binding dropdownlist in GriView first you need to find it by its id. In your sample code, you are trying to find something which is not dropdownlist.
Try this,
DropDownList ddList = (e.Row.FindControl("DropDownList1") as DropDownList);
if(ddList != null)
{
//your code
}

Dynamic postbackurl

I'm having a problem calling a modal in asp
I need to set the postbackurl of linkbutton4 from code behind depending on what is selected in the dropdownlist! I have tried putting the postbackurl directlty on the linkbuttons tag it worked but when i change it from the code behind it doesnt BTW i change it when the link button is clicked.
Code behind for the linkbutton:
protected void LinkButton4_Click(object sender, EventArgs e)
{
var a = (Control)sender;
GridViewRow row = (GridViewRow)a.NamingContainer;
string b = row.Cells[0].Text;
Session["C"] = b;
DropDownList ddl =(DropDownList)row.Cells[7].FindControl("DropDownList1");
Session["D"] = ddl.SelectedItem.Text;
LinkButton lb = (LinkButton)row.Cells[7].FindControl("LinkButton4");
if (Session["D"].ToString() == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
// Upload();
}
if (Session["D"].ToString() == "Download")
{
Download();
}
infogridbind();
}
Here is the code for aspx :
<asp:GridView ID="GridView2" runat="server" ondatabound="GridView2_DataBound"
onrowdatabound="GridView2_RowDataBound"
onrowcreated="GridView2_RowCreated"
onselectedindexchanged="GridView2_SelectedIndexChanged"
onrowcommand="GridView2_RowCommand" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="SizeSetID" SortExpression="SizeSetID"/>
<asp:BoundField DataField="Revision No." SortExpression="RevisionNo" HeaderText = "Revision No."/>
<asp:TemplateField HeaderText ="Image">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" onError = "this.style.display = 'none';" ImageUrl='<%#"~/ClientPoImage.ashx?autoId="+Eval("[SizeSetID]")%>' Width="50px" Height="40px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Size Name" SortExpression="SizeName" HeaderText = "Size Name"/>
<asp:BoundField DataField="Quantity Requested" SortExpression="QuantityRequested" HeaderText ="Quantity Requested"/>
<asp:BoundField DataField="Quantity Received" SortExpression="QuantityReceived" HeaderText="Quantity Received"/>
<asp:BoundField DataField="Balance" SortExpression="Balance" HeaderText="Balance"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate >
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem>Upload</asp:ListItem>
<asp:ListItem>Download</asp:ListItem>
<asp:ListItem>Edit</asp:ListItem>
<asp:ListItem>Delete</asp:ListItem>
<asp:ListItem>Request</asp:ListItem>
<asp:ListItem>Receive</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="LinkButton4" runat="server" onclick="LinkButton4_Click">GO</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can change PostBackUrl for LinkButton inside DropDownList.SelectedIndexChanged event like this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
var row = (GridViewRow)(ddl.NamingContainer);
var lb = (LinkButton)row.FindControl("LinkButton4");
if (ddl.SelectedValue == "Upload")
{
lb.PostBackUrl = "preprod_design.aspx#edit";
}
if (ddl.SelectedValue == "Download")
{
....
}
}
also you need change markup like this
....
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
....
Remove AutoPostBack="True" From DropDownList, and in the header of page <%# Page Title="data"... EnableEventValidation="false" %>
After That You just go to click event of Link button and then
GridViewRow gr = (GridViewRow)(((LinkButton)sender).NamingContainer);
DropDownList ddl = (DropDownList)gr.FindControl("DropDownList1");
If(ddl.SelectedValue =="Upload") // or u can use ddl.SelectedItem.Text
{
//Upload();
}
else if(ddl.SelectedValue == "Download")
{
//Download();
}

How to find a control in a row and bind it to data

I have a gridview and in the gridview i got a item template as follows
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
Now on every row in the gridview i need to bind this to the data, but i am having trouble finding it and binding it to the data.
The gridview has 4 templatefields with 1 itemtemplate within each template field like this
<asp:TemplateField HeaderText="Product Name" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Products" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlProductNames">
</asp:DropDownList>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" ItemStyle-HorizontalAlign = "Center" >
<ItemTemplate>
<asp:FileUpload runat="server" ID="image" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:CheckBox Text="Active" runat="server" ID="active" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
And I am trying to bind the drop down as follows
protected void Grid_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
// Bind Products
Product productManager = new Product();
TList<Product> dsProduct= productManager.GetAll();
DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList;
if (dsProduct != null)
{
DataView dvProduct = new DataView(dsProduct.ToDataSet(true).Tables[0]);
dvProduct.Sort = "name asc";
ddlProducts.DataSource = dvBrand;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
ListItem li = new ListItem("No Product Selected", "0");
ddlProducts.Items.Insert(0, li);
}
}
I am getting a out of index in the line DropDownList ddlProducts = Grid.Rows[e.Row.RowIndex].Cells[1].Controls[0].FindControl("ddlProductNames") as DropDownList; I am learning this process so i would appreciate some help in terms of what i am doing wrong and what i need to change. I would really appreciate any help.
You must use FindControl to find controls in a TemplateField. You also need to exclude the header-row:
protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
DropDownList ddlProducts = (DropDownList)e.Row.FindControl("ddlProductNames");
ddlProducts.DataSource = someDataSource;
ddlProducts.DataTextField = "name";
ddlProducts.DataValueField = "productId";
ddlProducts.DataBind();
}
}
You also don't need to call productManager.GetAll() for every row in the Grid. You only need to get the products for the current Row. If the source is the same for every row, you should create it before you bind the GridView as member-variable. Then you don't need to retrieve the same data for each row.

Categories