Grid view locking button by user id - c#

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")) %>

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

LinkButtons inside a Grid template to increment and decrement the lables value

protected void Gridproducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hp = new HyperLink();
hp = (HyperLink)e.Row.FindControl("linkSelectprd");
var Pid = DataBinder.Eval(e.Row.DataItem, "product_id").ToString();
var Catid = Request.QueryString["Cid"].ToString();
hp.NavigateUrl = "Sales.aspx?Cid="+Catid+"&"+"Pid="+Pid;
if (!IsPostBack && Request.QueryString["Pid"] != null)
{
this is the variable in which the value of quantity increments
int i=0;
lbltotalquantity.Text = i.ToString() + 1;
}
}
}
}
I use LinkButtons inside a Grid template. I want to be able to raise events when clicking the LinkButtons the value of lable is incremented on + link and decrementd on - link button as lable contains the quantity of Products added to invoice. How can I accomplish this?
I believe this is what you want....
You don't do the increment in RowDataBound because RowDataBound trigger when you are binding the GridView
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="up" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Label ID="lblProduct" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text="0"></asp:Label>
<asp:LinkButton ID="lbtnPlus" runat="server" Text="+" OnClick="lbtnPlus_Click"></asp:LinkButton>
<asp:LinkButton ID="lbtnMinus" runat="server" Text="-" OnClick="lbtnMinus_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gv" />
</Triggers>
</asp:UpdatePanel>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
string[] product = { "Dell", "Asus", "Acer", "Toshiba", "Fujishu", "VAIO" };
DataTable dt = new DataTable();
dt.Columns.Add("Product");
for (int i = 0; i < product.Length; i++)
dt.Rows.Add(product[i]);
gv.DataSource = dt;
gv.DataBind();
// Dispose
dt.Dispose();
}
}
private void DoTheMath(GridViewRow row, bool isAdd)
{
// Variable
bool isNumber = false;
int currentValue = 0;
// Find Control
Label lblQuantity = row.FindControl("lblQuantity") as Label;
// Check
if (lblQuantity != null)
{
// Check
if (lblQuantity.Text.Trim() != string.Empty)
{
isNumber = int.TryParse(lblQuantity.Text.Trim(), out currentValue);
// Check
if (isNumber)
{
// Is Add
if (isAdd)
currentValue++;
else
{
// Check cannot be less than 0
if (currentValue > 0)
currentValue--;
}
}
// Set to TextBox
lblQuantity.Text = currentValue.ToString();
}
}
}
protected void lbtnPlus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, true);
}
protected void lbtnMinus_Click(object sender, EventArgs e)
{
// Get
LinkButton lbtn = sender as LinkButton;
GridViewRow row = lbtn.NamingContainer as GridViewRow;
DoTheMath(row, false);
}

Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview

I have created user control named CRE.ascx,this control has 3 dropdownlist.
First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.
<table cellspacing="0" cellspading="0" style="width:550px;height:30px;">
<tr>
<td style="width:30%;">
<asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:30%;">
<asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td style="width:10%;">
<asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
width:65px;" ReadOnly="true"> </asp:TextBox>
</td>
</tr>
</table>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Get Ticket Type Values
dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
ddlCRE.DataSource = dbtickettype;
ddlCRE.DataValueField = "Type_ID";
ddlCRE.DataTextField = "Type_Name";
ddlCRE.DataBind();
ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
}
else
{
}
}
protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedTypeID = ddlCRE.SelectedValue.ToString();
try
{
if (selectedTypeID == "SLCT0000")
{
ddlDataPoints.Items.Clear();
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
//Binding Ticket Type values to Listbox
ddlDataPoints.DataSource = dbticketCategory;
ddlDataPoints.DataValueField = "Category_ID";
ddlDataPoints.DataTextField = "Category_Name";
ddlDataPoints.DataBind();
ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
//Clear Items
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCatID = ddlDataPoints.SelectedValue.ToString();
try
{
if (selectedCatID == "SLCT0000")
{
ddlErrorCode.Items.Clear();
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
//Binding Ticket Type values to Listbox
ddlErrorCode.DataSource = dbticketSubCategory;
ddlErrorCode.DataValueField = "Sub_Category_ID";
ddlErrorCode.DataTextField = "Sub_Category_Name";
ddlErrorCode.DataBind();
ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
//Clear Items
tbxErrorScore.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
try
{
if (selectedSubcatID == "SLCT0000")
{
tbxErrorScore.Text = string.Empty;
}
else
{
//Get Category Details
dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
////Binding Ticket Type values to Listbox
//ddlstIssue.DataSource = dbticketIssues;
//ddlstIssue.DataValueField = "IssueID";
//ddlstIssue.DataTextField = "Issue_Name";
//ddlstIssue.DataBind();
tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
}
}
catch (Exception ex)
{
}
}
then register directive and an instance of the user control added to the page.
In this main page, i have added one Gridview, user control UC1 and two buttons
included in the ItemTemplate.
<%# Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1" %>
<asp:UpdatePanel ID="MainUpdatePanel" runat="server">
<ContentTemplate>
<div id="dvsubCRE" class="dvsubCRE" runat="server">
<!-----[[[ GRIDVIEW ADDING CRE ]]]----->
<div id="dvAddingErrorInfo" class="dvAddingErrorInfo">
<!-- LOAD CRE DROPDOWN INFO GRID -->
<asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" >
<Columns>
<asp:BoundField DataField="RowNumber" />
<asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px">
<ItemTemplate>
<uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgbtnAddCRE" runat="server" Width="20px" Height="20px" value="" ImageUrl="~/Images/Tracker/add.png"
CommandName="ButtonAddCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px" value="" Visible="false" ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!-- LOAD CRE DROPDOWN INFO GRID CLOSE -->
</div>
<!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]----->
</div>
</ContentTemplate>
</asp:UpdatePanel>
When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
gvCREInfo.DataSource = dt;
gvCREInfo.DataBind();
}
else
{
}
}
catch (Exception ex)
{
}
}
protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
{
#region ADD NEW CRE ROW
if (e.CommandName == "ButtonAddCRERow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvCREInfo.Rows[index];
int count = gvCREInfo.Rows.Count;
DataRow drCurrentRow = null;
UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
for (int i = 0; i <= (count - 1); i++)
{
drCurrentRow = dtCurrentTable.NewRow();
dtCurrentTable.Rows.Add(drCurrentRow);
}
gvCREInfo.DataSource = dtCurrentTable;
gvCREInfo.DataBind();
}
#endregion
}
When i run this code working fine and i changed the first dropdownlist
it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
![enter image description here][1]
http://i.stack.imgur.com/wdYZv.jpg

Telerik Radgrid retrieve TextBox value that was dynamically added to column

From code I add a TextBox to a column
protected void grdPartsBeingMonitored_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
TextBox tbEditBox = new TextBox();
tbEditBox.Text = item[column].Text;
tbEditBox.Width = Unit.Pixel(50);
tbEditBox.ID = "editDemand";
item[column].Controls.Clear();
item[column].Controls.Add(tbEditBox);
}
}
}
Now how do I loop through each row and retrieve that rows value of the TextBox? Here's a start I believe:
foreach (GridDataItem item in grd1.MasterTableView.Items)
{
foreach (GridColumn column in item.OwnerTableView.RenderColumns)
{
if (column.UniqueName == "MyColumn")
{
//HOW TO RETRIEVE VALUE OF THE TEXTBOX HERE???
I tried this with no luck
foreach (Object c in item[column].Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox tbEditBox = (TextBox)c;
System.Diagnostics.Debug.Write(tbEditBox.Text);
}
}
Please try with the below code snippet.
ASPX
<div>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="Name" DataField="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Show edit" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Get edit value" OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="hide edit" OnClick="Button3_Click" />
</div>
ASPX.CS
public bool IsEditable
{
get
{
if (ViewState["IsEdit"] == null)
return false;
else
return (bool)ViewState["IsEdit"];
}
set
{
ViewState["IsEdit"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Name1");
dt.Rows.Add(2, "Name2");
dt.Rows.Add(3, "Name3");
RadGrid1.DataSource = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
IsEditable = true;
RadGrid1.Rebind();
}
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
Response.Write((item.FindControl("txtName") as TextBox).Text);
//perform your DB update here
}
}
protected void Button3_Click(object sender, EventArgs e)
{
IsEditable = false;
RadGrid1.Rebind();
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
Label lblName = item.FindControl("lblName") as Label;
TextBox txtName = item.FindControl("txtName") as TextBox;
lblName.Visible = !IsEditable;
txtName.Visible = IsEditable;
}
}
Let me know if any concern.

GridView OnRowUpdating does not fire due to CommandName="edit"

I already spend 2 days trying to solve this issue but no luck on how to solve this. I have a GridView to display data from the database then it also have functionality to modify and delete. This is the current ASP code for my GridView:
<asp:GridView ID="dgvSortKey" runat="server" AllowSorting="True" OnRowDataBound="gv_drb"
AutoGenerateColumns="False" AllowPaging="True" BackColor="White" BorderColor="#336666"
BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Horizontal"
Height="73px" AutoGenerateEditButton="True" OnRowEditing="dgvSortKey_RowEditing"
OnRowUpdating="dgvSortKey_RowUpdating" OnRowCancelingEdit="dgvSortKey_RowCancelingEdit"
OnSelectedIndexChanging="dgvSortKey_SelectedIndexChanging" OnPageIndexChanged="dgvSortKey_PageIndexChanged"
OnPageIndexChanging="dgvSortKey_PageIndexChanging" OnRowCommand="dgvSortKey_RowCommand"
OnRowDeleted="dgvSortKey_RowDeleted" OnRowUpdated="dgvSortKey_RowUpdated" Width="561px"
PageSize="15" DataKeyNames="KeyCode,KeyDescription">
<FooterStyle BackColor="White" ForeColor="#333333" />
<RowStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="LightCyan" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" OnClick="lnkdelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Instruction Key Code">
<ItemTemplate>
<asp:Label ID="lblValKeyCode" runat="server" Text='<%#System.Web.HttpUtility.HtmlEncode((string)Eval("KeyCode")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValKeyCode" runat="server" Text='<%#Bind("KeyCode") %>' MaxLength="10"
CausesValidation="false"></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" CssClass="GvBorderGreen" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblValKeyDescription" runat="server" Text='<%#System.Web.HttpUtility.HtmlEncode((string)Eval("KeyDescription")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValKeyDescription" runat="server" Text='<%#Bind("KeyDescription") %>'
Width="300" MaxLength="20" CausesValidation="false"></asp:TextBox>
</EditItemTemplate>
<ItemStyle CssClass="GvBorderGreen" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem is I can't update a certain record after click the Update Button, please see the image below:
When I'm in debug mode, it does not pass on OnRowUpdating event instead it passes to OnRowEditing. One thing that it makes me surprise is that when it fires to OnRowCommand, the CommandName set to "Edit" when Update Button is clicked. Please see the image below:
BTW this the Code Behind.
protected void dgvSortKey_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Currently Unreachable code due to unknown reason. RowUpdating not trigger even clicking Update Button in the GridView
// this.dvDetialContent.Visible = true;
List<SqlDbParameter> list = new List<SqlDbParameter>();
TextBox txtValKeyDescription = dgvSortKey.Rows[e.RowIndex].FindControl("txtValKeyDescription") as TextBox;
TextBox txtValKeyCode = dgvSortKey.Rows[e.RowIndex].FindControl("txtValKeyCode") as TextBox;
if (string.IsNullOrEmpty(txtValKeyCode.Text) || string.IsNullOrEmpty(txtValKeyDescription.Text))
{
string alert = "alert('Instruction KeyCode or KeyDecription should not be empty');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "scripting", alert, true);
}
else
{
//Trace.Write("txtKeyCode", HttpUtility.HtmlDecode(txtKeyCode.Text));
//Trace.Write("txtKeyDescription", txtKeyDescription.Text);
//Trace.Write("txtValKeyCode", txtValKeyCode.Text);
//Trace.Write("txtValKeyDescription", txtValKeyDescription.Text);
list.Add(new SqlDbParameter("#oldcode", HttpUtility.HtmlDecode(txtKeyCode.Text)));
list.Add(new SqlDbParameter("#oldname", HttpUtility.HtmlDecode(txtKeyDescription.Text)));
list.Add(new SqlDbParameter("#newcode", HttpUtility.HtmlDecode(txtValKeyCode.Text)));
list.Add(new SqlDbParameter("#newname", HttpUtility.HtmlDecode(txtValKeyDescription.Text)));
try
{
int result = CoreUtility.ExecuteNonQuery("update InstructionKey set KeyCode=#newcode, KeyDescription=#newname where KeyCode = #oldcode and KeyDescription = #oldname", list);
//Trace.Write("ResultValue", result.ToString());
}
catch (Exception ex)
{
string alert = "alert('Instruction KeyCode should not be duplicate');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "scripting2", alert, true);
}
}
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
this.txtKeyCode.Text = "";
this.txtKeyDescription.Text = "";
}
protected void dgvSortKey_RowEditing(object sender, GridViewEditEventArgs e)
{
// this.dvDetialContent.Visible = true;
//if (ViewState["updateFlag"] == null)
//{
//ViewState["editFlag"] = "forEdit";
//ViewState["editIndex"] = e.NewEditIndex;
dgvSortKey.EditIndex = e.NewEditIndex;
Label lblValKeyDescription = dgvSortKey.Rows[e.NewEditIndex].FindControl("lblValKeyDescription") as Label;
Label lblValKeyCode = dgvSortKey.Rows[e.NewEditIndex].FindControl("lblValKeyCode") as Label;
this.txtKeyCode.Text = lblValKeyCode.Text;
this.txtKeyDescription.Text = lblValKeyDescription.Text;
imgbtnFilter_Click(null, null);
//}
//else
//{
//RowUpdate((int)ViewState["editIndex"]);
//ViewState.Remove("updateFlag");
//ViewState.Remove("editFlag");
//ViewState.Remove("editIndex");
//}
}
protected void dgvSortKey_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
this.dvDetialContent.Visible = true;
Label lblValKeyDescription = dgvSortKey.Rows[e.NewSelectedIndex].FindControl("lblValKeyDescription") as Label;
Label lblValKeyCode = dgvSortKey.Rows[e.NewSelectedIndex].FindControl("lblValKeyCode") as Label;
this.txtKeyCode.Text = lblValKeyCode.Text;
this.txtKeyDescription.Text = lblValKeyDescription.Text;
}
protected void dgvSortKey_PageIndexChanged(object sender, EventArgs e)
{
}
protected void dgvSortKey_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
dgvSortKey.PageIndex = e.NewPageIndex;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
}
protected void dgvSortKey_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String jsScript = "";
jsScript += "var answer=confirm('Delete this Instruction Key?');\n";
jsScript += "if (!answer){\n";
jsScript += " document.getElementById('ctl00_cthContent_hdDelete').Value = 'DELETE';\n";
jsScript += "}\n";
//return;
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", jsScript, true);
List<SqlDbParameter> list = new List<SqlDbParameter>();
Label lblValKeyCode = dgvSortKey.Rows[e.RowIndex].FindControl("lblValKeyCode") as Label;
Label lblValKeyDescription = dgvSortKey.Rows[e.RowIndex].FindControl("lblValKeyDescription") as Label;
list.Add(new SqlDbParameter("#code", lblValKeyCode.Text));
list.Add(new SqlDbParameter("#name", lblValKeyDescription.Text));
CoreUtility.ExecuteNonQuery("DELETE FROM [InstructionKey] WHERE KeyCode=#code and KeyDescription=#name;", list);
Initial();
this.dvDetialContent.Visible = false;
dgvSortKey.EditIndex = -1;
imgbtnFilter_Click(null, null);
}
protected void dgvSortKey_RowCommand(object sender, GridViewCommandEventArgs e)
{
string id = e.CommandName;
}
protected void dgvSortKey_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
}
protected void gv_drb(object sender, GridViewRowEventArgs e)//
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkdelete");
//raising javascript confirmationbox whenver user clicks on link button
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox()");
}
}
While I have not figured out the bug, there is a workaround you may want to try.
Since the autogenerated edit button is giving you trouble, why not generate it yourself?
Like this:
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkedit" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
And handle it in your code behind:
void dgvSortKey_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Update")
{
}
}

Categories

Resources