I have a DropDownList that I would like to populate with column values from a DataBase. However, when I try to bind the DropDownList in code behind, the IDE keeps telling me:
"The name 'EqpCatDDL' does not exist in the current context"
I am not sure what is going on since I referred to the control by its ID. The following is the code:
aspx:
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false"
>
<Columns>
<asp:BoundField DataField="S/N" HeaderText="S/N" />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="EqpCatDDL" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:DropDownList ID="DescripDDL" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
c#:
public void Populate1()
{
string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection);
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
EqpCatDDL.DataSource = ddlValues;
EqpCatDDL.DataValueField = "EqpCateID";
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
Populate1();
}
The IDE can't find the EqpCatDDL control.
I am using the following: Visual Studio 2010, Microsoft SQL Server Management Studio 2008
I am working with a Visual Studio website
Use this code to bound data to dropdown without using RowDataBound.
Create a function that'll bind the Data to dropdown as follow and call it in Page_Load event
Public void fill_gridView_dropDown()
{
// your connection and query to retrieve dropdown data will go here
// this loop will go through all row in GridView
foreach(GridViewRow row in your_gridView_Name.Rows) {
DropDownList dropDown = (DropDownList)row.FindControl("dropDownList_id");
dropDown.DataSource = dataSource;
dropDown.DataValueField = "ValueField";
dropDown.DataTextField = "TextField";
dropDown.DataBind();
}
}
Please note that you have to bind GridView first, and then you have to bind your dropdown
your dropdown is in gridview so you can try with this code
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("EqpCatDDL'");
SqlCommand cmd = new SqlCommand("SELECT EqpCateID, EqpCat FROM EqpCategory", connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
EqpCatDDL.DataSource = ds;
EqpCatDDL.DataValueField = "EqpCateID";
EqpCatDDL.DataTextField = "EqpCat";
EqpCatDDL.DataBind();
}
}
You can't directly populate GridView's dropdownlist like this. You need to set datasource of GridView first i.e.
GridView1.DataSource = DataSource
And if you would like to access dropdownlist of this gridview, you can use RowDataBound event handler of GridView i.e.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking whether the Row is Data Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding the Dropdown control.
Control ctrl = e.Row.FindControl("EqpCatDDL");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
List lst = new List();
dd.DataSource = lst;
dd.DataBind();
}
}
}
Related
Can anybody give me some idea about how to create an ASP.NET form like Oracle tabular form.
Like I attached below.
<asp:GridView ID="OracleView" runat="server" AutoGenerateColumns="false" Width="100%" OnRowDataBound="OracleView_RowDataBound">
<Columns>
<asp:BoundField HeaderText="L id" DataField="id"></asp:BoundField>
<asp:TemplateField HeaderText="Concern">
<ItemTemplate>
<asp:DropDownList ID="ConcernList" runat="server" AutoPostBack="true" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Inside OracleView_RowDataBound you add data to your
protected void OracleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
string sql = "select Concern.name from Concern";
/*here your connection and method read list*/
List<string> ls = new List<string>();
ls = return your list data;
//ls.Insert(0, String.Empty);
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = e.Row.FindControl("ConcernList") as DropDownList;
if (ddl != null)
{
ddl.DataSource = ls;
ddl.SelectedValue = YourSelectedValueFromAnotherTable;
ddl.DataBind();
listDropdownMark = ls;
selectedMeltDropdown = YourSelectedValueFromAnotherTable;
}
}
}
Sorry if I don't help you.
My requirement is I need to access the Grid view data in a button click event.
I have Grid view with name gvData and have button named Update.
On click of update button I am saving data entered in the grid by user to DB.
Please suggest me in getting this done. Code snippets would be of great help.
I am populating the gridview on page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt;
String SQL = "SELECT * FROM tbl_Class";
string sConstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable();
da.Fill(dt);
}
}
}
gvMarks.DataSource = dt;
gvMarks.DataBind();
}
}
<asp:GridView ID="gvMarks" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:TemplateField HeaderText="One">
<ItemTemplate>
<asp:TextBox ID="txt1" runat="server" Text='<%# Bind("One") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Two">
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server" Text='<%# Bind("TWO") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Three">
<ItemTemplate>
<asp:TextBox ID="txtThree" runat="server" Text='<%# Bind("THREE") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Four">
<ItemTemplate>
<asp:TextBox ID="txt4" runat="server" Text='<%# Bind("FOUR") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FIVE">
<ItemTemplate>
<asp:TextBox ID="txtFive" runat="server" Text='<%# Bind("FIVE") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SIX">
<ItemTemplate>
<asp:TextBox ID="txt6" runat="server" Text='<%# Bind("SIX") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnUpdae" runat="server" Text="Update Marks" OnClick="btnUpdae_Click" />
protected void btnUpdae_Click(object sender, EventArgs e)
{
//Need to acces the grid view rows and colums here
}
fetch row one by one by foreach or for loop and save the data.
Click This to know more about save the gridview data to your database
You can go with the following approach-
TextBox txt=(TextBox)gvMarks.Rows[i].Cells[0].FindControl("txt1");
string txtOne= txt.Text;
You can use this with for loop and for all the text boxes. Then insert/update the data taken in string variable like txtOne(above used) into the table.Then bind the grid again. You can hit the following link for another solution.
http://forums.asp.net/t/1647616.aspx?Get%20Value%20of%20TextBox%20inside%20the%20GridView%20in%20c%20
I hope this can make your work done.
Try this.
protected void btnUpdae_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)gvMarks.Rows[rowIndex].Cells[0].FindControl("txt1");
TextBox box2 = (TextBox)gvMarks.Rows[rowIndex].Cells[1].FindControl("txt2");
TextBox box3 = (TextBox)gvMarks.Rows[rowIndex].Cells[2].FindControl("txt3");
TextBox box4 = (TextBox)gvMarks.Rows[rowIndex].Cells[3].FindControl("txt4");
TextBox box5 = (TextBox)gvMarks.Rows[rowIndex].Cells[4].FindControl("txt5");
TextBox box6 = (TextBox)gvMarks.Rows[rowIndex].Cells[5].FindControl("txt6");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text+ "," + box4.Text + "," + box5.Text+ "," + box6.Text);
rowIndex++;
}
//Call the method for executing inserts or update
}
}
}
i have one column in grid view named Town. and based on town list i want to add Area Dropdownlist
area dropdown list must show all the areas list that contains town table....
for example vijayawada town contains gannavaram and autonagar as areas
and kollur town contains tenali and bajipet as areas list
please help me i am not getting any idea.
i used the code for grid view is as follows
<asp:BoundField HeaderText="Town" DataField="town"></asp:BoundField>
<asp:TemplateField HeaderText = "Area">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("area") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
i want to display based on town data field regarding areas list have to display in Area's dropdown list
thank you....
HTML markup
> <asp:GridView ID="GridView1" runat="server"
> AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
> <Columns>
> <asp:BoundField HeaderText="Name" DataField="ContactName" />
> <asp:TemplateField HeaderText = "Country">
> <ItemTemplate>
> <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("area") %>' Visible = "false" />
> <asp:DropDownList ID="ddlCountries" runat="server">
> </asp:DropDownList>
> </ItemTemplate>
> </asp:TemplateField>
> </Columns> </asp:GridView>
Like this you can populate data into your grid view
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT area FROM tablename");
GridView1.DataBind();
}
}
to get data
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
I have 2 gridview on my page: on GridView1 I have a column with select link, Id and Name which looks like this:
Select | Id | Name
select | 101 | Jack
select | 102 | Cath
Now, what I am trying to do is let's say, I clicked the select from the first row which is Jack, now my GridView2 will display the products ordered by Jack which looks like this:
Id | ProductID
101 | 111
101 | 222
101 | 333
and if Cath whom I selected, GridView2 will change the display products which ordered by Cath:
Id | productID
102 | 111
102 | 333
102 | 555
In short, I am trying to populate GridView2 based on the selected row from the GridView1. I am using asp.net with C#.
When you are selecting the row in 1st grid then in selectIndexChanged event of your grid take the value of the primary key ID and store in hiddenField
If you have used Datakey then use
SelectedDatakey
take the value of SelectedDatakey and store in hiddenfield
protected void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
hiddenfield1.value = CustomersGridView.SelectedDataKey.Value;
}
Now In your query to fill the 2nd grid pass the 1st grid's key value which you have stored in hiddenfield in where condition and populate the second grid according to your query result
This is my sample code......
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> DataList = new List<Data>() { new Data { id = 1, id2 = 2 }, new Data { id = 3, id2 = 4 } };
GridView1.DataSource = DataList;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow ) btn.NamingContainer;
Label slNoLabel = (Label) row.FindControl("slNoLabel");
// function to get data based on label vlue
GridView2.DataSource=GetData(slNoLabel.Text);
GridView2.DataBind();
}
DataTable GetData(string value)
{
DataTable tbl = new DataTable ();
// Calling DB
return tbl;
}
}
public class Data
{
public int id { get; set; }
public int id2 { get; set; }
}
and in the UI
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Select" OnClick="Button1_Click" Text="Select" />
<asp:Button ID="Button2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server"></asp:GridView>
</div>
You can add an onClick method on the link button you added for "Select".
<asp:GridView ID="Gridview1" runat="server"
AllowPaging="true" PageSize="15" RowStyle-Wrap="true" EmptyDataRowStyle-ForeColor="Red"
AutoGenerateColumns="false" GridLines="None">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:LinkButton ID ="li_Select" runat="server" Text="Select" OnClick="li_Select_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_ID" Text='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_Name" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now Filter the data or fetch the data from the database on the basis of clicked row ID.
protected void li_Select_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;
Label lbl_ID = (Label)row.FindControl("lbl_ID");
// You can fetch the data from the database on the basis of selected User ID .
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Product_ID");
for (int i = 100; i <= 110; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = i;
dr["Product_ID"] = "P_" + i;
dt.Rows.Add(dr);
}
// In this method you pass the id of the user, and datatable fetched from the database of all products. or you can pass the id in the storedprocedure to get data of selected user only and then bind it here .
GetData(lbl_ID.Text,dt);
}
protected void GetData(string ID, DataTable dt)
{
DataView dv = dt.DefaultView;
dv.RowFilter = "ID=" + ID;
Gridview2.DataSource = dv;
Gridview2.DataBind();
}
The best way of doing this in my opinion is to use UpdatePanel to bind the second grid, using this you will have an advantage, no postback (it is postback actually, but the user wont notice it..)...
And if you don't use the UpdatePanel, then there is no way you can see the data after binding it in the postback (unless you are doing it through Javascript, which is a hassle)...Here is the sample code for achieving it:
ASPX Page:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView2" runat="server" >
<Columns>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="asd" Text='Select' runat="server" OnClick="link_click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected override void PageLoad(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getDataSource();
GridView1.DataBind();
}
}
private DataTable getDataSource()
{
SqlConnection conn = new SqlConnection("Server=192.168.1.1;DATABASE=dummy;UID=****;PWD=*****;"); //Example connString
SqlCommand comm = new SqlCommand("SELECT * FROM Table1", conn);
SqlDataAdapter ad = new SqlDataAdapter(comm);
DataTable ta = new DataTable();
ad.Fill(ta);
return ta;
}
protected void button_click(object sender, EventArgs e)
{
LinkButton asd = (LinkButton)sender;
GridViewRow row = (GridViewRow)asd.NamingContainer; //Gets the selected Row
string user_id = row.Cells[2].Text; //Use this to get any value you want.
//Can now use the user_name to get the data for the grid 2, and update the panel
GridView2.DataSource = getDataSource2(user_id);
GridView2.DataBind();
UpdatePanel1.Update();
}
private DataTable getDataSource2(string user_id)
{
string sql = "SELECT * FROM TABLE2 WHERE user_id = #user_id";
SqlConnection conn = new SqlConnection("Server=sqlserver\\sql2008;DATABASE=esm80;UID=sa;PWD=sa;"); //Example connString
SqlCommand comm = new SqlCommand();
comm.CommandText = sql;
comm.Parameters.AddWithValue("#name", user_id);
comm.Connection = conn;
SqlDataAdapter ad = new SqlDataAdapter(comm);
DataTable ta = new DataTable();
ad.Fill(ta);
return ta;
}
Now the explaination, the UpdatePanel of GridView2 is there to update the gridView2 once the data is binded to it (this will show the newly binded data). The UpdatePanel of GridView1 is there to prevent the postback, from the link button.
Hope this answers your question.
How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind is below.
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
You need to use SelectedIndexChanged handler to show selected value:
Markup:
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
Code-behind:
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
I had a similar problem using the DropDownLists in GridView. My solution was to adjust the onLoad for the dropdown so that it wouldn't re-write the DropDownList on every post back. This way if there's something there then it won't re-populate it.
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place
this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>