I have an item template in a GridView and I want to create a dropdown for each row and bind it to a value retrieved from the database.. but I am not sure how to do this.. this is what i have so far.. but not sure where to put the code to populate the drop down per row..
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity" SelectedValue='<%#
(DataBinder.Eval(Container.DataItem,"Quantity")) %>'>
</asp:DropDownList>
</ItemTemplate>
and in code behind, not sure how to or where to put this so that it is created on every row..
public void BindMyQuantity()
{
for (int i = 1; i < 15; i++)
{
ddlMyQuantity.Items.Add(i.ToString());
}
}
Also i am not sure if i can do that, but the code is not complaining.. adding SelectedValue in the asp declaration
You can use OnRowDataBound to dynamically bind your dropdown:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var dropdownList = (DropDownList)e.Row.FindControl("ddlMyQuantity");
for (int i = 1; i < 15; i++)
{
dropdownList.Items.Add(i.ToString());
}
dropdownList.SelectedValue =
Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Quantity"));
}
}
Add binding:
<asp:GridView ... OnRowDataBound="GridView_RowDataBound">
...
</asp:GridView>
As per my knowledge, the best option would be to write this code in "RowDataBound" event of the Grid. See sample code below.
protected void GridView_RowDataBound(..)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
DropDownList ddl = e.Row.FindControl("ddlMyQuantity") as DropDownList;
if (ddl != null)
{
for (int i = 1; i < 15; i++)
{
ddl.Items.Add(i.ToString());
}
}
}
}
In the aspx page, provide this
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlMyQuantity"></asp:DropDownList>
</ItemTemplate>
Hope this Helps!!
<asp:TemplateField HeaderText="Type Cargo" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataValueField="DESCRIPTION"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Code Behind will look like this...
Dim rowId As DropDownList
For i As Integer = 0 To gridView1.Rows.Count - 1
Dim gridrow As GridViewRow = gridView1.Rows(i)
rowId = DirectCast(gridrow.FindControl("DropDownList1"), DropDownList)
Dim dt As DataTable = Get_List()
rowId.DataSource = dt
rowId.DataBind()
Next
Get_List is a Function that returns a DataTable
Related
Default.aspx
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="typeHobby" runat="server">
<asp:ListItem style="display:none">--Select--</asp:ListItem>
<asp:ListItem Value="Sports">Sports</asp:ListItem>
<asp:ListItem Value="FineArt">Fine Arts</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="nameSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details of participation">
<ItemTemplate>
<asp:TextBox ID="detailSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Distinction achieved">
<ItemTemplate>
<asp:TextBox ID="distSport" style="margin:2px" CssClass="cap" pattern="[A-Za-z]{2,15}" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Whether still intrested">
<ItemTemplate>
<asp:DropDownList ID="intrestSport" runat="server">
<asp:ListItem style="display:none">--Select--</asp:ListItem>
<asp:ListItem Value="yes">Yes</asp:ListItem>
<asp:ListItem Value="no">No</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="addHobby" runat="server" Text="Add" OnClick="ButtonAdd_Click_Hobby" CausesValidation="false" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs
protected void ButtonAdd_Click_Hobby(object sender, EventArgs e)
{
addHobby();
}
protected void addHobby()
{
// MessageBox.Show("add hobby");
try
{
int rowIndex = 0;
if (ViewState["HoobyTable"] != null)
{
MessageBox.Show("if true");
DataTable dtHobbyTable = (DataTable)ViewState["HoobyTable"];
DataRow drHobbyRow = null;
if (dtHobbyTable.Rows.Count > 0)
{
MessageBox.Show(dtHobbyTable.Rows.Count.ToString());
for (int i = 1; i <= dtHobbyTable.Rows.Count; i++)
{
//extract the TextBox values
MessageBox.Show("loop");
DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
MessageBox.Show("Hello" + txh1.Text);
drHobbyRow = dtHobbyTable.NewRow();
drHobbyRow["Slno"] = i + 1;
dtHobbyTable.Rows[i - 1]["hoType"] = txh1.Text;
dtHobbyTable.Rows[i - 1]["Name"] = txh2.Text;
dtHobbyTable.Rows[i - 1]["Detail"] = txh3.Text;
dtHobbyTable.Rows[i - 1]["Distinction"] = txh4.Text;
dtHobbyTable.Rows[i - 1]["Interest"] ="interest";
rowIndex++;
}
dtHobbyTable.Rows.Add(drHobbyRow);
ViewState["HoobyTable"] = dtHobbyTable;
hobbyGrid.DataSource = dtHobbyTable;
hobbyGrid.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
}
catch (Exception e)
{
// MessageBox.Show(e.ToString());
}
//Set Previous Data on Postbacks
SetPreviousDataHobby();
}
private void SetPreviousDataHobby()
{
int rowIndex = 0;
if (ViewState["HoobyTable"] != null)
{
DataTable dt = (DataTable)ViewState["HoobyTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
MessageBox.Show("type hobby" + dt.Rows[i]["hoType"].ToString());
txh1.Text = dt.Rows[i]["hoType"].ToString();
txh2.Text = dt.Rows[i]["Name"].ToString();
txh3.Text = dt.Rows[i]["Detail"].ToString();
txh4.Text = dt.Rows[i]["Distinction"].ToString();
txh5.Text = dt.Rows[i]["Interest"].ToString();
rowIndex++;
}
}
}
}
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values.
Parameter name: index'
-> got an error like above in line:
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[5].FindControl("intrestSport");
(line from SetPreviousDataHobby() function)
I believe this should point you in the right direction
Rows and Columns of DataGrid starts at index 0
hobbyGrid.Rows[rowIndex].Cells[5] indicates that there are 6 columns, do you think that's true ?
The error message simply indicates that you are accessing an index that is outside the limits of the data structure.
You can validate how many columns are available at row[0] by hobbyGrid.Rows[0].Cells.Count-1; Cells[5] should not exceed this
OR
You can also check number of colums from table like int cols= dtHobbyTable.Columns.Count
Error is because, you are accessing cells from 1 through 5. so at Cells[5] its throwing out of range exception. Please modify your code to start from 0:
DropDownList txh1 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[0].FindControl("typeHobby");
TextBox txh2 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[1].FindControl("nameSport");
TextBox txh3 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[2].FindControl("detailSport");
TextBox txh4 = (TextBox)hobbyGrid.Rows[rowIndex].Cells[3].FindControl("distSport");
DropDownList txh5 = (DropDownList)hobbyGrid.Rows[rowIndex].Cells[4].FindControl("intrestSport");
Side but related notes:
1) There is another issue that you may encounter after fixing this error:
adding data row outside forloop. So, you are basically overwriting data row in for loop and adding just one row. Ignore me if that is what you expected. Otherwise, move the below line inside for loop.
dtHobbyTable.Rows.Add(drHobbyRow);
2) Another issue is you are running for loop on an item which you are updating. Instead its good to have for loop on hobbyGrid.Rows.Count.
i have gridview with 3 columns and 100 rows. and one submit button out of gridview.
here first 2 column is bounded field and 3rd one is Label (templatefield) .
Now, I want to change status of 3rd column and display it to gridview when loop run.
i want to
when i=0 then i want to change label's value to "SUCESS" and display on Gridview,
i=1 then i want to change label's value to "SUCESS" and display on Gridview,
and so on till i=100.
Gridview
<asp:GridView ID="GvCategoryLive" runat="server" AutoGenerateColumns="False" EmptyDataText="No Records Found !" >
<Columns>
<asp:BoundField DataField="UnitName" HeaderText="Unit Name" />
<asp:BoundField DataField="CreateDate" HeaderText="Created Date" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="UnitMesurement_Id" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am trying something like this
protected void btnSave_Click(object sender, EventArgs e)
{
if (btnSave.Text == "Save")
{
for (int i = 0; i < GvCategoryLive.Rows.Count; i++)
{
System.Threading.Thread.Sleep(9000);
GvCategoryLive.Rows[i].Cells[2].Text = "Success";
}
}
}
I really dont remember the gridviews and asp.net webforms but
You may use setTimeout in javascript
var rowCount = 100;// get row count here
for(int i = 0; i < rowCount ; i++)
{
setTimeout($('#cell'+i).html('Success'), 9000);
}
You could try like this:
protected void btnSave_Click(object sender, EventArgs e)
{
if (btnSave.Text == "Save")
{
foreach(GridViewRow row in GvCategoryLive.Rows) {
if(row.RowType == DataControlRowType.DataRow) {
Label UnitMesurement_Id= row.FindControl("UnitMesurement_Id") as Label ;
UnitMesurement_Id.Text = "Success";
}
}
}
}
Because you are not setting the value of a cell but label inside that cell, you should change this-
GvCategoryLive.Rows[i].Cells[2].Text = "Success";
into-
Label UnitMesurement_Id = GvCategoryLive.Rows[i].FindControl("UnitMesurement_Id") as Label;
UnitMesurement_Id.Text = "Success";
Am using the below code to bind the dropdown data from another table. And also refer that control name using rowindex. But it always return null.And also return the error message.
`Object reference not set to an instance of an object.`
Am using the two method, but both return the control name null
First code:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control ctrl = e.Row.FindControl("DDL_STATUS_FT"); //It always return null
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
DataSet7TableAdapters.sp_getall_trv_masterTableAdapter TA = new DataSet7TableAdapters.sp_getall_trv_masterTableAdapter();
DataSet7.sp_getall_trv_masterDataTable DS = TA.GetData();
dd.DataTextField = "fld_TName";
dd.DataValueField = "fld_id";
dd.DataSource = DS;
dd.DataBind();
}
}
}
Second :
In databind function
if (DS.Rows.Count > 0)
{
GridView2.DataSource = DS;
GridView2.DataBind();
foreach (GridViewRow grdRow in GridView2.Rows)
{
DataSet7TableAdapters.sp_getall_trv_masterTableAdapter TA1 = new DataSet7TableAdapters.sp_getall_trv_masterTableAdapter();
DataSet7.sp_getall_trv_masterDataTable DS1 = TA1.GetData();
// Nested DropDownList Control reference is passed to the DrdList object. This will allow you access the properties of dropdownlist placed inside the GridView Template column.
DropDownList drdList = (DropDownList)(GridView2.Rows[grdRow.RowIndex].Cells[4].FindControl("DDL_STATUS_FT"));//It always return null
// DataBinding of nested DropDownList Control for each row of GridView Control.
drdList.DataSource = DS1;
drdList.DataValueField = "fld_id";
drdList.DataTextField = "fld_TName";
drdList.DataBind();
}
}
Please help me to do this..
<asp:TemplateField ItemStyle-Width="100px" HeaderText="TYPE">
<ItemTemplate>
<asp:DropDownList ID="DDL_STATUS" runat="server" AutoPostBack="true" Enabled="false" >
</asp:DropDownList>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDL_edit_STATUS" runat="server" AutoPostBack="true" SelectedValue='<%# Eval("fld_Type") %>'>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DDL_STATUS_FT" runat="server" AutoPostBack="true">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
The DropDown "DDL_STATUS_FT" is in Footer Template..You must check it as follow..
if(e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ctrl =(DropDownList)e.Row.Cells[CellIndex].FindControl("DDL_STATUS_FT");
}
Try to find your control by cell and cellIndex like...
Control ctrl = e.Row.Cells[yourCellIndex].FindControl("DDL_STATUS_FT");
EDITED2
you must have dropdownlist in aspx code in gridview item-template
you are finding using e.row.findcontrol without declaring it so abusively it return null
so, fist add dropdownlist into your gridview
here is a sample of your dropdownlist
<asp:TemplateField ItemStyle-Width="30px" HeaderText="DDL_STATUS_FT">
<ItemTemplate>
<asp:Dropdownlist ID="DDL_STATUS_FT" runat="server" />
</ItemTemplate>
</asp:TemplateField>
if you got null ctrl
Control ctrl = e.Row.FindControl("DDL_STATUS_FT"); //It always return null
then make sure in your aspx code DDL_STATUS_FT Control is runat="server"
I have a GridView with a TemplateField column that I put PlaceHolder controls in. During the DataBound event for the GridView I dynamically add a few CheckBoxes to the PlaceHolder. That works fine and displays as expected.
My problem is that during the RowUpdating event the PlaceHolder contains no controls; my CheckBoxes are missing. I also noticed that they're missing during the RowEditing event.
I want to be able to get the values of the CheckBoxes during the RowUpdating event so I can save them to the database.
Here's some example code. I've trimmed out a lot to reduce size, but if you want to see specifics just ask and I'll be happy to add more.
HTML:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
ondatabound="gridView_DataBound" onrowupdating="gridView_RowUpdating"
onrowediting="gridView_RowEditing" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
<EditItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="updateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
// This method works fine, no obvious problems here.
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder)row.FindControl("countriesPlaceHolder");
// Create a CheckBox for each country and add it to the PlaceHolder
foreach (Country country in this.Countries)
{
bool isChecked = holidays.ElementAt(i).Countries.Any(item => item.ID == country.ID);
var countryCheckBox = new CheckBox
{
Checked = isChecked,
ID = country.Abbreviation + "CheckBox",
Text = country.Abbreviation
};
placeHolder.Controls.Add(countryCheckBox);
}
}
}
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = gridView.Rows[e.NewEditIndex].FindControl("countriesPlaceHolder").Controls;
gridView.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = ((PlaceHolder)gridView.Rows[e.RowIndex].FindControl("countriesPlaceHolder")).Controls;
// This is where I'd grab the values from the controls, create an entity, and save the entity to the database.
gridView.EditIndex = -1;
BindData();
}
This is the article that I followed for my data binding approach: http://www.aarongoldenthal.com/post/2009/04/19/Manually-Databinding-a-GridView.aspx
You need to call your BindData() method on page load.
"Dynamic controls or columns need to be recreated on every page load, because of the way that controls work. Dynamic controls do not get retained so you have to reload them on every page postback; however, viewstate will be retained for these controls."
See Cells in gridview lose controls on RowUpdating event
Also in the article you linked, there is an ItemTemplate and an EditItemTemplace because they have different displays, i.e. read only and editable. Yours are the same so I think you could simplify your design:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ondatabound="gridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" Text="Edit" onclick="editButton_Click" ></asp:LinkButton>
<asp:LinkButton ID="updateButton" runat="server" Text="Update" onclick="updateButton_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder) row.FindControl("countriesPlaceHolder");
var countryCheckBox = new CheckBox
{
Checked = true,
ID = "auCheckBox",
Text = "Aus",
Enabled = false
};
placeHolder.Controls.Add(countryCheckBox);
var editButton = (LinkButton)row.FindControl("editButton");
editButton.CommandArgument = i.ToString();
var updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.CommandArgument = i.ToString();
updateButton.Visible = false;
}
}
protected void editButton_Click(object sender, EventArgs e)
{
LinkButton editButton = (LinkButton) sender;
int index = Convert.ToInt32(editButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.Visible = true;
editButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
checkbox.Enabled = true;
// Get value and update
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
LinkButton updateButton = (LinkButton)sender;
int index = Convert.ToInt32(updateButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton editButton = (LinkButton)row.FindControl("updateButton");
editButton.Visible = true;
updateButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
// Get value and update
checkbox.Enabled = false;
}
}
If you want to be it enabled from the get go, just remove the enabled checks and you can delete your edit button.
Hope that helps.
I have a gridview as :
<asp:GridView ID="gvAppRejProfiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Resumes
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnResumes" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i have a list of resume names (string format) that i want to add as the text of the linkbutton "lbtnResumes" for all the resume names that i have in a string array.
make use of FindControl() mehod ....to search control
void gvAppRejProfiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton bl =
(LinkButton)e.Row.FindControl("lbtnResumes");
}
}
for (int count = 0; count < gvAppRejProfiles.Rows.Count; count++)
{
LinkButton lbtnResumes = (LinkButton)gvAppRejProfiles.Rows[count].FindControl("lbtnResumes");
if (lbtnResumes.Text == "resume")
{
// Store and perform any operation
}
}