ASP.NET Editing a GridView row - c#

3 Dropdownlists in same row when I edit.
When 1 dropdownlist has a selection, the other 2 should go to index of 0 (the empty one).
Example of my code:
<asp:TemplateField HeaderText="Project" SortExpression="Project">
<ItemTemplate>
<%#Eval("Project") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ProjectDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ProjectDropDownList_Changed" AppendDataBoundItems="true"
DataSourceID="ProjectDataSource" DataTextField="navn" DataValueField="navn">
<asp:ListItem>-- choose one --</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My SelectionChanged even handler:
protected void ProjektDropDownList_SelectionChanged(object sender, EventArgs e)
{
DropDownList project = (DropDownList) GridView1.Rows[GridView1.SelectedIndex].FindControl("ProjectDropDownList");
DropDownList kunde = (DropDownList)GridView1.Rows[GridView1.SelectedIndex].FindControl("KundeDropDownList");
DropDownList øvrige = (DropDownList)GridView1.Rows[GridView1.SelectedIndex].FindControl("ØvrigeDropDownList");
if(project.SelectedIndex >= 0 && kunde != null && øvrige != null) {
kunde.SelectedIndex = 0;
øvrige.SelectedIndex = 0;
}
}
I get a nullpointer when trying to fetch other controls in the same row... How do I fix this?

I'm not sure it's the SelectedIndex that you're looking for. Isn't there an EditItemIndex which you should be using?

Related

System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index' in asp.net

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.

How to multiselect values in listbox into template filed asp. net

I try to multiselect values in listbox into template field, when it is in edit mode. Is there a way to do it?
I tried something like this. I add HiddenField to bind there a values and then w JS code I want to select selected values (I can do it but I dont have a class in HiddenField so it isn't a good solution).
Also I don't know is there a chance to do it by server side becasue it didn't recognize Id's of mine Listbox
<asp:TemplateField HeaderText="Conditions" ItemStyle-Width="100px">
<EditItemTemplate>
<asp:HiddenField runat="server" ID="hdn_dd_conditions" class="bottom" Value='<%# Bind("conditions") %>' />
<asp:ListBox ID="dd_conditions" runat="server" CssClass="conditions" SelectionMode="Multiple" multiple="multiple">
<asp:ListItem Value="Value1" Text="Text2"></asp:ListItem>
<asp:ListItem Value="Value2" Text="Text2"></asp:ListItem>
<asp:ListItem Value="Others" Text="Others"></asp:ListItem>
</asp:ListBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("conditions") %>' Font-Size="10px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Any ideas?
You need to access the ListBox in the RowDataBound event of the GridView
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow and in edit mode
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) > 0)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//use findcontrol to locate the listbox and cast it
ListBox lb = e.Row.FindControl("dd_conditions") as ListBox;
//loop all the items in a listbox
for (int i = 0; i < lb.Items.Count; i++)
{
//check the values and set the Selected property
if (lb.Items[i].Value == row["conditions"].ToString())
{
lb.Items[i].Selected = true;
}
}
}
}

Dropdownlist in edit mode of a gridview

In my application in c#, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
<asp:TemplateField HeaderText="Gender">
<ItemTemplate>
<asp:Label ID="gender" runat="server" Text='<%# Eval("gender").ToString() %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDL_genderList" runat="server">
<asp:ListItem Value="" Text="---"></asp:ListItem>
<asp:ListItem Value="M" Text="M"> </asp:ListItem>
<asp:ListItem Value="F" Text="F"> </asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
But when I press the 'Edit' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
I need selected value in dropdownlist it's the value which displays in Label gender.
Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck.
I tried this:
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView dRowView = (DataRowView)e.Row.DataItem;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList genderList = (DropDownList)e.Row.FindControl("DDL_genderList");
genderList.SelectedValue = dRowView[1].ToString();
}
}
You have to find Label from TemplateField (DataRow) and DropDownList from EditTemplate (EditRowState) as like:
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find gender from label which is inside ItemTemplate
string lblgender = ((Label)e.Row.FindControl("gender")).Text;
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
// find gender list from dropdownlist which is inside EditTemplate
DropDownList genderList = (DropDownList)e.Row.FindControl("DDL_genderList");
genderList.SelectedIndex =
genderList.Items.IndexOf(genderList.Items.FindByValue(lblgender));
}
}
}
I know this is very late answer but it can help to the OP.

Grid view Dropdown list data binding error

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"

Adding a drop down in itemtemplate and populating value dynamically

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

Categories