How to access gridview cells of a particular selected and checked row. Below are the codes
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True">
<Columns>
<asp:TemplateField HeaderText="IsApproved">
<ItemTemplate>
<asp:CheckBox ID="chkApproved" runat="server" CommandName="Approve" />
</ItemTemplate></asp:TemplateField></Columns></asp:GridView>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="Approve" Value="1"></asp:ListItem>
<asp:ListItem Text="Reject" Value="2"></asp:ListItem>
</asp:RadioButtonList>
The datasource of gridview is set by strongly typed data sets on Page_Load. Now on btnSubmit I want to insert the selected row into my database table if it is checked
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedValue == "1")
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("chkApproved") as CheckBox;
if (chk.Checked)
{
DataSet1TableAdapters.tbl_ApproveTableAdapter ta = new DataSet1TableAdapters.tbl_ApproveTableAdapter();
DataSet1.tbl_ApproveDataTable dt = new DataSet1.tbl_ApproveDataTable();
ta.Insert()// here I've to specify the cells of GV
}
}
}
}
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
I've two issues here
i) To access the gridview cells if the row is checked in the checkbox
ii) On my GV select it is automatically set to AutoPostback which I want to disable as it is clearing the selected checkboxes.
.
Update panel automatically post back but you can disable autopostback by using AsyncPostBackTrigger. Set the ChildrenAsTriggers property to true and the UpdateMode property to Conditional
<asp:UpdatePanel ID="myPanel" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
// put your code here to avoid autopost back
</ContentTemplate>
</asp:UpdatePanel>
Another way to disable autopostback is to set AutoPostBack to false...
<asp:RadioButtonList ID="RadioButtonList1" AutoPostBack="False">
You need to bind gridview like this
if (!Page.IsPostBack)
{
GridView1.DataSource = source;
GridView1.DataBind();
}
and try. Sure it will give your expected result.
Try to use CommandArgument='<%# Container.DataItemIndex %>' attribute in the .
It return index of selected GridView row.
Then on click event you can write logic to fetch value of specific rows and columns of selected gridview row.
For example if you want to access 3rd column of 1st row you can write
GridView.Rows[0].Cells[2].Text in click event or checkedchange event to fetch value.
Related
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" CssClass="outdata">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Center" ItemStyle-CssClass="profiledata" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" style="width: 50px !important;" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" OnCheckedChanged="chkSelect_CheckedChanged" runat="server" />
<asp:HiddenField runat="server" ID="hdnAssid" Value='<%# Eval("Asset_ID") %>' />
</ItemTemplate>
<ItemStyle Width="5px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Stop" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlGrdStops"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Suppose I have 2 columns in Gridview.
1. CheckBox
2. DropDownList
What Should be the code in the OnCheckedChange event of checkbox that whenever i check it the dropdownlist of the same row should be filled.
I tried RowDataBound event of gridview but the data is too large,so its take a long time in processing and it unnecessarily checks every rows checkbox.
Plase help since I am new.
Thanks in advance. :)
You can use the NamingContainer of the CheckBox to locate the DropDownList in the same row. PS set AutoPostBack to true on the CheckBox.
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
//cast the sender back to a checkbox
CheckBox cb = sender as CheckBox;
//get the current gridviewrow from the checkbox namingcontainer
GridViewRow row = cb.NamingContainer as GridViewRow;
//use findcontrol to locate the dropdownlist in that row
DropDownList ddl = row.FindControl("ddlGrdStops") as DropDownList;
//add the items to the dropdownlist
ddl.Items.Add(new ListItem() { Text = "DropDownList found", Value = "1" });
}
I have an editable GridView.
I have an AddRow button, which adds a row which consists of 3 text boxes and one dropdown list.
Also, I have a Delete button, which removes the whole row when clicked.
Whenever I click on AddRow button, the selection of my dropdownlist doesn't persist, the selected value is realigned to the very first item.
Below are the codes:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Serial No">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Col1">
<ItemTemplate>
<asp:TextBox runat="server" ID="txt1" Text='<%# Eval("Column1") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Col2">
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server" Text='<%# Eval("Column2") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Col3">
<ItemTemplate>
<asp:TextBox ID="txt3" runat="server" Text='<%# Eval("Column3") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DropDown">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField='<%# Eval("Column4") %>'>
<asp:ListItem>London</asp:ListItem>
<asp:ListItem>Paris</asp:ListItem>
<asp:ListItem>New Delhi</asp:ListItem>
<asp:ListItem>New York</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAddNewRow" runat="server" Text="AddRow" OnClick="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSavetoDB" runat="server" Text="save" OnClick="btnSavetoDB_Click" />
EDITED CODE:
List<string> newList = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var table = CreateDataTable();
table.Rows.Add("", "", "");
BindGridView(table);
}
}
//Called on AddRow button click
protected void Add(object sender, EventArgs e)
{
var newTable = PopulateTableFromGridView();
newTable.Rows.Add("", "", "");
BindGridView(newTable);
}
private DataTable PopulateTableFromGridView()
{
var table = CreateDataTable();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[i].FindControl("txt1");
TextBox box2 = (TextBox)GridView1.Rows[i].FindControl("txt2");
TextBox box3 = (TextBox)GridView1.Rows[i].FindControl("txt3");
DropDownList ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
table.Rows.Add(box1.Text, box2.Text, box3.Text,ddl.SelectedItem.Text);
}
newList.Add(ddl.SelectedItem.Text);//add selecteditems to a global list
return table;
}
//Sets the first empty row to the grid view
private DataTable CreateDataTable()
{
var dt = new DataTable
{
Columns = { "Column1", "Column2", "Column3","Column4" }
};
return dt;
}
private void BindGridView(DataTable table)
{
GridView1.DataSource = table;
GridView1.DataBind();
for(int i=0;i<GridView1.Rows.Count-1;i++)
{
DropDownList ddl2=(DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl2.ClearSelection();
ddl2.Items.FindByText(newList[i]).Selected = true;
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var dt = PopulateTableFromGridView();
if (dt.Rows.Count > 1)
{
dt.Rows[e.RowIndex].Delete();
}
BindGridView(dt);
}
The first screenshot, I have selected NewDelhi from the dropdownlist, which is the 3rd item:
The second screenshot, wherein a new row has been added after AddRow button is clicked, the dropdownlist is realigned in the first row, shows London.
How to make the code persist the dropdownlist selection when AddRow and Delete button is clicked?
I tried disabling the AutoPostBack property of the dropdownlist to false, but to no effect.
Experts please help.
SUCCESSFUL SCREENSHOTS:
I have solved the problem after some R&D.
I have created a new instance of dropdownlist after the gridview is bound, and in that new instance, I am preserving the previous selection using a List from the PopulateGridView method.
Please see the edit of the code.
Hope this helps some body.
Every time you hit the addrow button you are performing a postback.
every postback rebuilds then entire page including the grid based on your table. You can see that in your own code.
But part of this is that the controls within each row are rebuilt too. This includes your DDL's, but you are not saving/restoring the selected values from each drop down. More correctly, the selected values are saved but are invalidated when you recreate the table. you have to handle the RowDatabound event and in each row restore the selected value in the ddl.
But you may have a bigger problem. You are using the same instance of the DDL in each row. this may cause selection/persistence issues. If you find that selecting an item from the ddl causes all rows to have the same selected item, that's the problem in action.
Take a look at the rendered output for your ddl's and make sure the id's are unique for each row.
if the ddl has it's own datasource then you need to create a new instance of a DropDownlist in each row and assign it the same datasource rather than using find control.
if the control has it's list items hard coded then you should just check for unique ddl id's
I have a gridview on a .NET forms application, and on postback, I am not seeing the values entered in the textbox within a gridview.
ASPX:
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="false" ShowHeader="false" DataKeyNames="ItemId" EnableViewState="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtItem" runat="server" Text="0" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemId" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btn" Text="Submit" OnClick="btn_OnClick" OnClientClick="javascript:return someClientStuff();" />
Code Behind:
protected void btn_OnClick(object sender, System.EventArgs e)
{
foreach(GridViewRow row in gvItems.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
var itemId = Convert.ToInt32(gvItems.DataKeys[row.RowIndex].Values[0]);
var itemValue = ((row.Cells[0].FindControl("txtItem") as TextBox).Text;
}
}
I am seeing itemId populated for each row, but itemValue is always empty string.
Been a while since I worked on a forms application, any help is appreciated!
I will assume that the DataBind of the GridView is not in if(!IsPostBack). Add this to the Page_Load
if(!IsPostBack)
{
gvItems.DataSource = soruceOftheGrid
gvItems.DataBind();
}
On the button click, try to store the values in the view state and within page load event, try to assign the viewstate back to the grid view as for each postback, page load event is called. Its good to assign the values back to grid view within page load, this will help you to retain the values you have entered.
I'm using a dropdownlist inside a detailsview and it populates well, but when I do a insert there is a postback so I'm trying to bind the DDL again but the values are lost somehow.
My aspx:
<asp:UpdatePanel ID="InsertPanel" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableHeaderRow SkinID="tableheaderrowSkin">
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell BackColor="DarkGray" BorderColor="DarkGray" BorderWidth="1" Width="300">
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="nFuturesId"
DataSourceID="FutureCommodityODS" DefaultMode="Insert" OnItemInserting="DetailsView1_ItemInserting"
SkinID="detailsviewSkin" OnItemInserted="DetailsView1_ItemInserted" EnableModelValidation="True">
<BrummerComp:SortableDropDownList ID="DropDownListFuturesInsert" runat="server" SkinID="BCdropdownlistSkin">
</BrummerComp:SortableDropDownList>
</asp:DetailsView>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
</asp:UpdatePanel>
I populate the DDL in Page_Load:
protected new void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindDropDownList();
}
//DetailsView1.DataBind();
}
BindDropDownList:
private void BindDropDownList()
{
var paperFutureList = (List<PaperFutures>)DataManager.GetPaperFutures();
var ddl = (DropDownList)DetailsView1.FindControl("DropDownListFuturesInsert");
ddl.DataSource = paperFutureList;
ddl.DataValueField = "nFuturesID";
ddl.DataTextField = "ShortNameAndFutureNameAndFutureId";
ddl.DataBind();
}
The problem is when I do a insert in my detailsview the DDL is loses it's values. I have tried databind the detailsview but then the values won't load at all.
The method BindDropDownList works well in Page_Load the first time. Also tried putting the methodcall outside !IsPostBack to always populate it but that doesn't work either.
I have checked GetPaperFutures() and it works well every time, so the problem is somewhere else, but I can't find where.
I was facing the similar problem. Eventually, I have found the solution!
Just call the BindDropDownList() in Page_PreRender event.
It works successfully!
I have a Gridview control and I have placed a RadioButton in the itemtemplate. When I click a button I'm trying to get the checked property of the radio button. But When I click the checked property is always returning false. Please look into the below code and let me know where I'm making mistake.
aspx Code
<asp:GridView ID="gvDepartments" runat="server" AutoGenerateColumns="False" GridLines="None"AllowPaging="true" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rdbtn" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lbl" runat="server"></asp:Label>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="btn_Click" CssClass="button small"/>
Code Behind on button click
foreach (GridViewRow row in gvDepartments.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
RadioButton rd = (RadioButton)row.FindControl("rdbtn");
lbl.Text += rd.Checked.ToString();// +rd1.Checked.ToString();
}
}
Result will be False always in the label always. I'm using Ajaxcontroltoolkit in the application, Above controls are present in the update panel and I even tried to placing button and event in the triggers but the result is same. Please help.
Regards,
Nuthan A R
When do you assign and load the DataSource of the GridView? Note that you should do that only if(!IsPostBack) and not on every postback. So use the Page.IsPostBack property.
So assuming that you're using Page_Load for this:
protected void Page_Load(Object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindGridView(); // method that assigns DataSource and calls DataBind
}
}