DropdownList with Checkbox in a GridView - c#

Here is my current grid view.
<asp:GridView ID="grdIndexGroupMap" runat="server" AutoGenerateColumns="False" DataKeyNames="IndexName"
OnRowCancelingEdit="grdIndexGroupMap_RowCancelingEdit" OnRowDataBound="grdIndexGroupMap_RowDataBound"
OnRowEditing="grdIndexGroupMap_RowEditing" OnRowUpdating="grdIndexGroupMap_RowUpdating"
OnRowCommand="grdIndexGroupMap_RowCommand" ShowFooter="True" OnRowDeleting="grdIndexGroupMap_RowDeleting"
CellPadding="1" CellSpacing="1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--IndexName--%>
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="cmbIndexName" runat="server" DataTextField="LocationName" DataValueField="IndexId"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblIndexName" runat="server" Text='<%# Eval("IndexName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewIndexName" runat="server" DataTextField="IndexName" DataValueField="IndexId"></asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How do replace the DropDownList with a dropdown where I can select multiple items?
A checkboxlist in dropdownlist or a listbox with multiselect in dropdown. When selected will show comma seperated values.
Tried a couple of ways but wont work.
here is my databound method:
protected void grdIndexGroupMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbIndexName = (DropDownList)e.Row.FindControl("cmbIndexName");
if (cmbIndexName != null)
{
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewIndexName = (DropDownList)e.Row.FindControl("cmbNewIndexName");
cmbNewIndexName.DataSource = _Indexes;
cmbNewIndexName.DataBind();
}
}
I am using ASP.Net, C#

How about:
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:PlaceHolder id="phListContainer" runat="server" />
</EditItemTemplate>
then in your code-behind:
if (e.Row.RowType == DataControlRowType.DataRow)
{
phListContainer = (PlaceHolder)e.Row.FindControl(phListContainer);
if (phListContainer != null)
{
//Adding a DropDownList
var cmbIndexName = new DropDownList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
phListContainer.Controls.Add(cmbIndexName);
// OR
//Adding a CheckBoxList;
cmbIndexName = new CheckBoxList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
phListContainer.Controls.Add(cmbIndexName);
}
}
Then you can get the controls by
var cbList = (CheckBoxList)e.Row.FindControl(phListContainer).Controls[0];
and then you can loop through and find the checked boxes
for(int i = 0; i < cbList.Items.Count; ++i)
{
if(cbList.Items[i].Selected)
//Do stuff
}

Related

DropDownList and pagination conflict in gridview in .NET C#

this is my gridview in .NET c# with pagination
<asp:GridView ID="gvProducts" AutoGenerateColumns="False" EmptyDataText="ko" EnableViewState="true"
runat="server" DataKeyNames="ID" CssClass="mGrid" HorizontalAlign="Center"
OnRowDataBound="gvProducts_RowDataBound"
AllowPaging="True" PageSize="10"
OnPageIndexChanging="OnPageIndexChanging">
<AlternatingRowStyle CssClass="altrows" />
<Columns>
<asp:BoundField DataField="Nr" HeaderText="Nr." ReadOnly="true" HtmlEncode="false"
ItemStyle-CssClass="ddl_Class_new" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList ID="ddlstatus" runat="server" CssClass="pure-u-23-24"
AutoPostBack="true" OnSelectedIndexChanged="ddlstatus_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/aspnet/img/bot_back_1.gif"
CommandArgument="First" CommandName="Page" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="/aspnet/img/bot_back.gif"
CommandArgument="Prev" CommandName="Page" />
Page
<asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" CssClass="ddl_Class"
OnSelectedIndexChanged="ddlPages_SelectedIndexChanged">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="/aspnet/img/bot_next.gif"
CommandArgument="Next" CommandName="Page" />
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="/aspnet/img/bot_next_1.gif"
CommandArgument="Last" CommandName="Page" />
</PagerTemplate>
</asp:GridView>
on this gridview i have added this dropdownlist ddlstatus
<asp:TemplateField HeaderText="Status" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:DropDownList ID="ddlstatus" runat="server" CssClass="pure-u-23-24"
AutoPostBack="true" OnSelectedIndexChanged="ddlstatus_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
when the dropdownlist ddlstatus is changed i need open new webpage on the browser
protected void ddlstatus_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ebb = (DropDownList)sender;
GridViewRow gvr = (GridViewRow)ebb.NamingContainer;
string dvalue = gvr.Cells[1].Text;
ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('newpage.aspx?ID=" + dvalue.ToString() + "');", true);
}
but the new webpage on the browser is opened also if try change page on gridview
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = gvProducts.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
gvProducts.PageIndex = ddlPages.SelectedIndex;
BindData();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = gvProducts.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
gvProducts.PageIndex = 0;
break;
case "Prev":
gvProducts.PageIndex = intCurIndex - 1;
break;
case "Next":
gvProducts.PageIndex = intCurIndex + 1;
break;
case "Last":
gvProducts.PageIndex = gvProducts.PageCount - 1;
break;
}
gvProducts.DataBind();
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}
this is the the RowDataBound event
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = gvProducts.PageCount.ToString();
for (int i = 1; i <= gvProducts.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = gvProducts.PageIndex;
if (gvProducts.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (gvProducts.PageIndex + 1 == gvProducts.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
i don't understand why this happens?
how to do resolve this?
thanks in advance for any help

Nested GridViews in ASP.Net using C# problem with change page

I am trying to open my nested gridview for a single Parent Row and gets correctly open with one single record of the child row.
The paging of the rows is provided in the main gridview.
My problem is the page change, when I try change page I have this error :
GridView paging event gvProducts_PageIndexChanging not firing
How to do resolve this ?
My code below.
Thanks in advance for any help.
Code Markup
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="CustomerID" OnRowDataBound="gvProducts_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
</Columns>
<PagerTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/aspnet/img/bot_back_doppio.gif"
CommandArgument="First" CommandName="Page" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="/aspnet/img/bot_back.gif"
CommandArgument="Prev" CommandName="Page" />
Page
<asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" CssClass="ddl_Class"
OnSelectedIndexChanged="ddlPages_SelectedIndexChanged">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="/aspnet/img/bot_next.gif"
CommandArgument="Next" CommandName="Page" />
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="/aspnet/img/bot_next_doppio.gif"
CommandArgument="Last" CommandName="Page" />
</PagerTemplate>
</asp:GridView>
Code Behind
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerId = gvProducts.DataKeys[e.Row.RowIndex].Value.ToString();
sql = #String.Format(" SELECT ... ");
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(sql);
gvOrders.DataBind();
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = gvProducts.PageCount.ToString();
for (int i = 1; i <= gvProducts.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = gvProducts.PageIndex;
if (gvProducts.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (gvProducts.PageIndex + 1 == gvProducts.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = gvProducts.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
gvProducts.PageIndex = ddlPages.SelectedIndex;
BindData();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = gvProducts.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
gvProducts.PageIndex = 0;
break;
case "Prev":
gvProducts.PageIndex = intCurIndex - 1;
break;
case "Next":
gvProducts.PageIndex = intCurIndex + 1;
break;
case "Last":
gvProducts.PageIndex = gvProducts.PageCount - 1;
break;
}
gvProducts.DataBind();
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}
Please try this :
[Solution] The GridView 'GridView1' fired event PageIndexChanging which wasn't handled
I hope I was helpful.

Grid view locking button by user id

I have a gridview in my project where like twitter you can see other peoples post but i want to allow users to change there posts and because of that near every post i putted an edit button. Now my problem is i cant lock the button if the user didnt post that tweet. can you show me how i can check if the users id (a given variable) matches the tweet user id (hidden field) i thought on using the for each loop but i cant succeed using it.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating"
onrowdeleting="GridView1_RowDeleting" >
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="lbl_Username" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<asp:Label ID="lbl_Tweet" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Tbx_Tweet" runat="server" Text='<%#Eval("TweetText") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="Pic" runat="server" ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_TweetID" runat="server" Text='<%#Eval("TweetID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_UserID" runat="server" Text='<%#Eval("UserID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate >
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Tweets : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bool f = true;
if (!IsPostBack)
{
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//Response.End();
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// row.Cells[7].Visible = false;
//}
}
BindGridview();
//foreach (GridViewRow row in GridView1.Rows)
//{
// Label l = row.FindControl("UserID") as Label;
// Response.Write(l.Text);
// //if (int.Parse(l.Text.ToString()) != 1)
// //{
// // Response.End();
// // row.Cells[7].Visible = false;
// //}
//}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = 1;
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.Like(int.Parse(l.Text), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.ReTweet(int.Parse(l.Text), userId);
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridview();
}
public void BindGridview()
{
int userId = 1;
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, false);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
//int i = 0,x=0,y=0;
//DataTable dt1 = new DataTable();
//foreach (DataRow row in dt.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// dt1.Rows.Add(dt.Rows[x][4]);
// x++;
// }
//}
//foreach (DataRow row in dt1.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// if (obj.ToString() == userId.ToString())
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = true;
// }
// else
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = false;
// }
// i++;
// }
//}
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label TweetID = GridView1.Rows[e.RowIndex].FindControl("lbl_TweetID") as Label;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("Tbx_Tweet") as TextBox;
TweetHelper.Updatetweet(int.Parse(TweetID.Text), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
You have more options to do it.
Create RowDataBound event handler and set up edit button Visibile/Enable property:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label userIdLbl = (Label)e.Row.FindControl("lbl_UserID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = currentUserId == Convert.ToInt32(userIdLbl.Text);
}
}
Create a method in your code behind to check if the userId is currentUserId and add the attribute Visible/Enable to your edit button in gridview template:
Visible='<%# IsCurentUserId((int)Eval("UserID")) %>

Getting row index of checked row

I am trying to do when the checkbox column in my gridview is marked, I get the row index. My gridview is in a repeater and when I setup the gridview, I put a DataKeyNames:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:Panel ID="pBody1" runat="server" CssClass="cpBody">
<asp:Label ID="lblBodyText1" runat="server" />
<!-- Grid view to show products based on each category -->
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" Width="998px" CellPadding="4" ForeColor="#333333" GridLines="None" ShowHeader="False" DataKeyNames="id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="cbCheckRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="Name" ItemStyle-Width="600px" />
<asp:BoundField DataField="categoryName" HeaderText="Category" />
<asp:TemplateField HeaderText="Quantity" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="tbQuantity" runat="server" Width="60" Text='<%# DataBinder.Eval(Container.DataItem, "inventoryQuantity") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
<asp:CollapsiblePanelExtender ID="cpe1" runat="server" TargetControlID="pBody1" CollapseControlID="pHeader1"
ExpandControlID="pHeader1" Collapsed="true" ImageControlID="imgArrows1"
CollapsedImage="~/Images/downarrow.jpg"
ExpandedImage="~/Images/uparrow.jpg" TextLabelID="lblHeaderText1" CollapsedText="Show"
ExpandedText="Hide" CollapsedSize="0"
ScrollContents="false">
</asp:CollapsiblePanelExtender>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="lbnConfirm" runat="server" class="btn dark" style="float: right" OnClick="lbnConfirm_Click">Confirm</asp:LinkButton>
When my lbnConfirm is onclick, I perform this to get the row index and store them into a list:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
GridView gv = (GridView)Repeater1.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
GridViewRow row = gv.SelectedRow;
string prodID = this.gv.DataKeys[row].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
}
}
}
When I run the page, it told me object reference is not set to an instance at this line:
foreach (GridViewRow gr in gv.Rows)
Also the gv of this line:
string prodID = this.gv.DataKeys[row].Value.ToString();
told me that the gv does not contain a definition of missing reference. I thought I declared at the code above?
Edited Portion:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
tempList.Add(prodID);
for (int count = 0; count < tempList.Count; count++)
{
lblTest.Text = tempList[count] + ",";
}
}
}
}
}
}
Your approach is right, however you need to consider few more things:
You have to loop through the Repeater's items and find the Panel in
each item.
You have to find the GridView inside the Panel, not in the Repeater.
You have to find the DataKey Value by RowIndex, not by row.
EDIT : To test, add a Label outside the repeater:
<asp:Label ID="lblTest" runat="server" Text=""></asp:Label>
Also change the code to display Id in the label.
After rewriting lbnConfirm_Click() method, it should look like below:
protected void lbnConfirm_Click(object sender, EventArgs e)
{
List<string> tempList = new List<string>();
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Panel pnl = item.FindControl("pBody1") as Panel;
GridView gv = pnl.FindControl("gvProduct") as GridView;
foreach (GridViewRow gr in gv.Rows)
{
CheckBox cb = (CheckBox)gr.Cells[0].FindControl("cbCheckRow");
if (cb.Checked)
{
//GridViewRow row = gv.SelectedRow;
string prodID = gv.DataKeys[gr.RowIndex].Value.ToString();
List<DistributionStandardPackingUnitItems> distSPUList = new List<DistributionStandardPackingUnitItems>();
//Store the prodIDs into list
tempList.Add(prodID);
}
}
}
}
lblTest.Text = string.Join(",", tempList);
}
The code above worked fine in my test! Only you have to be careful not to rebind the repeater at postback in Page_Load().
Hope it helps!
get the row index in the RowDataBound event :
protected void gvProduct_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.commandName=="select")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
CheckBox chk = (CheckBox)e.Row.FindControl("cbCheckRow");
int code = Convert.ToInt32(this.gvProduct.DataKeys[e.Row.RowIndex].Value);
}
}
}

row updating in gridview not working

Gridview update is not happening after I edit it. Used breakpoints and checked, its showing the same existing values which is there before editing. I am not getting any kind of error. Have used Store Procedure to update the Gridview. Please go through the code and help me sort out this problem.
aspx code
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False"
OnRowEditing="gvData_RowEditing"
OnRowDataBound="gvData_RowCreated"
OnRowCreated="gvData_RowCreated"
OnRowCancelingEdit="gvData_RowCancelingEdit"
OnRowUpdating="gvData_RowUpdating"
Style="text-align: center; margin-left: 0px;" Height="160px"
Width="657px" BackColor="#DEBA84" BorderColor="#DEBA84"
orderStyle="None" BorderWidth="0px" CellPadding="3" CellSpacing="2"
DataKeyNames="BtnID" Font-Names="Calibri" ForeColor="#CC3300"
EmptyDataText="No Records Found!!!"
CaptionAlign="Left" HorizontalAlign="Left"
>
<AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" BorderStyle="None" />
<Columns>
<asp:TemplateField HeaderText="BtnID" >
<ItemTemplate>
<asp:Label ID="lblBtnID" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("BtnID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LogdInUsername" >
<ItemTemplate>
<asp:Label ID="lblLogdInUsername" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
Text='<%#Eval("LogdInUsername") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:Label ID="lblYear" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Height="24px" Text='<%# Eval("Year") %>' Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Month">
<ItemTemplate>
<asp:Label ID="lblMonth" runat="server" ForeColor="#003366"
Font-Names="Calibri" Font-Size="Small" Text='<%# Eval("Month") %>' Height="24px" Width="20px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server"
ForeColor="#003366" Font-Names="Calibri" Text='<%# Eval("Comments") %>' Font-Size="Small" Height="24px"
Width="20px" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtComments" runat="server"
Width="300px" Text='<%# Bind("Comments") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False"
BorderStyle="None" />
<EmptyDataRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"
HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
<SortedAscendingCellStyle BackColor="#FFF1D4" HorizontalAlign="Left"
VerticalAlign="Middle" Wrap="False" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
cs code
protected void Page_Load(object sender, EventArgs e)
{
DTO objc = new DTO();
string str = Environment.UserName;
GrdGetComments();
if (!IsPostBack)
{
GetYear();
GetMonth();
GrdGetComments();
UserPrincipal up1 = GetUserPrincipal(str);
Session["Username"] = str;
Session["Name"] = up1.Name;
LblName.Text = Session["Username"].ToString();
objc.Name = LblName.Text;
LblLogdInUsername.Text = Session["Name"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
LblDateTime.Text = DateTime.Now.ToString();
LblCompany.Text = "";
objc.Company = LblCompany.Text;
}
}
public static UserPrincipal GetUserPrincipal(String userName)
{
UserPrincipal up = null;
PrincipalContext context = new PrincipalContext(ContextType.Domain);
up = UserPrincipal.FindByIdentity(context, userName);
if (up == null)
{
context = new PrincipalContext(ContextType.Machine);
up = UserPrincipal.FindByIdentity(context, userName);
}
if (up == null)
throw new Exception("Unable to get user from Domain or Machine context.");
return up;
}
protected void GetYear()
{
DTO objc = new DTO();
{
DrpForYear.DataSource = obj.GetYear();
DrpForYear.DataTextField = "Year";
DrpForYear.DataBind();
}
}
protected void GetMonth()
{
DTO objc = new DTO();
{
DrpForMonth.DataSource = obj.GetMonth(); ;
DrpForMonth.DataTextField = "Month";
DrpForMonth.DataBind();
}
}
public void GrdGetComments()
{
DTO objc = new DTO();
{
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
DTO objc = new DTO();
int Flag = 0;
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.DateTime = DateTime.Now;
objc.Comments = TxtComments.Text;
objc.Company = LblCompany.Text;
LblName.Text = Session["Name"].ToString();
objc.Name = LblName.Text;
objc.Year = DrpForYear.SelectedItem.Text;
objc.Month = DrpForMonth.SelectedItem.Text;
objc.ViewPreference = RadView.SelectedItem.Text;
int X = obj.InsertButtonComment(objc);
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
if (Flag == 1)
{
LblSuccess.Visible = true;
LblSuccess.Text = "Comment Saved";
}
else
{
LblErr.Visible = true;
LblErr.Text = "Failed To Save Comment!!!";
}
objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
DataSet GrdVC = obj.GetButtonComment(objc);
DataView GrdViewC = new DataView();
GrdViewC.Table = GrdVC.Tables[0];
gvData.DataSource = GrdViewC;
gvData.DataBind();
TxtComments.Text = "";
DrpForYear.ClearSelection();
DrpForMonth.ClearSelection();
RadView.Text = "";
}
protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
gvData.EditIndex = e.NewEditIndex;
GrdGetComments();
}
protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvData.EditIndex = -1;
GrdGetComments();
}
protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DTO objc = new DTO();
Label lblBtnID = (Label)gvData.Rows[e.RowIndex].FindControl("lblBtnID");
Label lblLogdInUsername = (Label)gvData.Rows[e.RowIndex].FindControl("lblLogdInUsername");
Label lblYear = (Label)gvData.Rows[e.RowIndex].FindControl("lblYear");
Label lblMonth = (Label)gvData.Rows[e.RowIndex].FindControl("lblMonth");
Label lblComments = (Label)gvData.Rows[e.RowIndex].FindControl("lblComments");
TextBox txtComments = (TextBox)gvData.Rows[e.RowIndex].FindControl("TxtComments");
LblLogdInUsername.Text = Session["Username"].ToString();
objc.LogdInUsername = LblLogdInUsername.Text;
objc.Comments = TxtComments.Text;
objc.BtnID = Convert.ToInt32(Session["BtnID"]);
int Flag = 0;
int X = obj.UpdategvData(objc);
{
if (X >= 0)
{
Flag = 1;
}
else
{
Flag = 0;
}
}
if (Flag == 1)
{
LblSuccss.Visible = true;
LblSuccss.Text = "Comment Updated";
}
else
{
LblErrr.Visible = true;
LblErrr.Text = "Failed To Update Comment!!!";
}
}
public int UpdategvData(InLogDTO b)
{
DBAccess db = new DBAccess();
SqlParameter objParam = new SqlParameter("#LogdInUsername", b.LogdInUsername);
objParam.Direction = ParameterDirection.Input;
objParam.Size = 50;
db.Parameters.Add(new SqlParameter("#Comments", b.Comments));
db.Parameters.Add(new SqlParameter("#BtnID", b.BtnID));
db.Parameters.Add(objParam);
int retval = db.ExecuteNonQuery("UpdategvData");
if (retval >= 1)
{
int i = 0;
return i;
}
else
{
return -1;
}
}
stored procedure
ALTER PROCEDURE [dbo].[UpdategvData]
#LogdInUsername nvarchar(50) ,
#Comments nvarchar(50),
#BtnID int
AS
Update dbo.Button_Comments
Set Comments = #Comments
Where LogdInUsername = #LogdInUsername and ViewPreference = 'Public' and
Comments = #Comments and BtnID = #BtnID;
GrdGetComments(); is running in your Page_Load, which binds the gridview again after editing (without saving). This needs to be in the (!IsPostBack).
Page life cycle indicates that Page_Load will always run before any other button clicks:
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx
You need to bind your gridview inside the if (!IsPostBack).
The stored procedure also needs a return value, for example adding a return to the end will allow you to grab this within your C# code.

Categories

Resources