Why Asp:GridView calls button click method in server side? - c#

In my case i have asp:gridview with OnRowCommand calls server method but when i try to refresh my page manually then it also calls OnRowCommand method, i don't know where is the actual problem.
My Code:.aspx
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="CUG_OnSelectedIndexChanged" OnRowCommand="CugSubmit_onserverclick1" EnableViewState="true"BorderStyle="Solid" BorderColor="Gray" BorderWidth="1px" EditRowStyle-BorderStyle="Solid" EditRowStyle-BorderWidth="1px" EditRowStyle-BorderColor="Gray" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="Gray" RowStyle-BorderStyle="Solid" RowStyle-BorderColor="Gray" RowStyle-BorderWidth="1px" EmptyDataRowStyle-BorderStyle="Solid" EmptyDataRowStyle-BorderColor="Black" EmptyDataRowStyle-BorderWidth="1px" SortedAscendingHeaderStyle-BorderStyle="Solid" SortedAscendingHeaderStyle-BorderColor="Black" SortedAscendingHeaderStyle-BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Driver ID">
<ItemTemplate>
<asp:Label ID="lbl_Dri_Name" runat="server" Text='<%# Eval("VehicleNo") %>' Visible="false"></asp:Label>
<asp:TextBox ID="Dri_Name" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dedicated">
<ItemTemplate>
<asp:Label ID="lbl_Vehitype" runat="server" Text='<%# Eval("VehicleType") %>' Visible="false"></asp:Label>
<asp:CheckBox ID="Vehitype" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="ProcessThis" Text="Submit" />
<asp:ButtonField CommandName="Select" ItemStyle-Width="30" Text="delete" HeaderText="Delete" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
</ItemTemplate>
<FooterStyle HorizontalAlign="left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns></asp:gridview>
My code:.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetCUGList();
}
}
protected void CugSubmit_onserverclick1(object sender, GridViewCommandEventArgs e)
{
DL.CustomerProfile ObjInput = new CustomerProfile();
BL.CustomerInputBL ObjCustomerInputBL = new CustomerInputBL();
if (e.CommandName == "ProcessThis")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.VehiNo = textBox.Text;
ObjInput.Update = "Insert";
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*****/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insert Request Sent to Admin')", true);
GetCUGList();
}
}
AddNewRowToGrid();
}
else if (e.CommandName == "ProcessThisUpdate")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.Update = "Update";
ObjInput.VehiNo = textBox.Text;
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*******/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Update Request Sent to Admin')", true);
GetCUGList();
}
}
}
}

Related

How to read dynamically added texbox's value in gridview

I need to create dynamic form, which i will have to create the textbox, textarea,dropdown etc, based on the field type.
Now, I have successfully created this dynamic textbox etc using my rowdatabound.
My problem is I could not retrieve the textbox value entered when the save button is clicked.
My aspx file
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
//DYNAMICALLY ADDING TEXTBOX
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" ItemStyle-CssClass="hiddencol" />
</Columns>
</asp:GridView>
My code behind file
protected void Page_Load(object sender, EventArgs e)
{
GetTemplateComponent();
}
public void GetTemplateComponent()
{
StringBuilder sb;
DataSet ds;
sb = new StringBuilder();
sb.AppendLine("select * from template where tc='0002' order by Sequence");
ds = Conn.DataAdapter(CommandType.Text, sb.ToString());
gv.DataSource = ds;
gv.DataBind();
}
protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string value = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FieldType"));
if (value == "Date" || value == "TextBox")
{
TextBox TextBox1 = new TextBox() { ID = "TextBox1", EnableViewState = false, CssClass = "form-control" };
e.Row.Cells[3].Controls.Add(TextBox1);
}
if (value == "TextArea")
{
TextBox DateTextBox = new TextBox() { EnableViewState = false, CssClass = "form-control", TextMode = TextBoxMode.MultiLine, Rows = 5, Columns = 50 };
e.Row.Cells[3].Controls.Add(DateTextBox);
}
if (value == "Content")
{
TextBox ContentAreaControl = new TextBox()
{
TextMode = TextBoxMode.MultiLine,
EnableViewState = false,
Columns = 10,
MaxLength = 150,
Height = 200,
CssClass = "Content-container",
};
e.Row.Cells[3].Controls.Add(ContentAreaControl);
}
}
}
protected void SaveTemplateDetails(object sender, EventArgs e)
{
foreach (GridViewRow row in gv.Rows)
{
FieldValue.Value = row.Cells[3].Text.ToString();
*//I DONT KNOW HOW TO READ THE VALUE*
}
}
I just want to know how is the proper way to read this dynamically created textbox
Thank you
ASPX Page Code.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDataBound="gv_RowDataBound1">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" />
</Columns>
</asp:GridView>
Code behind file
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string fieldType = e.Row.Cells[2].Text;
TextBox txtData = e.Row.Cells[3].FindControl("TextBox1") as TextBox;
switch (fieldType)
{
case "Date":
case "TextBox":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
break;
case "TextArea":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
txtData.TextMode = TextBoxMode.MultiLine;
txtData.Rows = 5;
txtData.Columns = 50;
break;
case "Content":
txtData.TextMode = TextBoxMode.MultiLine;
txtData.EnableViewState = false;
txtData.Columns = 10;
txtData.MaxLength = 150;
txtData.Height = 200;
txtData.CssClass = "Content-container";
break;
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveTemplateDetails();
}
private void SaveTemplateDetails()
{
foreach (GridViewRow row in gv.Rows)
{
foreach (Control c in row.Cells[3].Controls)
{
TextBox txtDate = c as TextBox;
if (txtDate != null)
{
string data = txtDate.Text;
}
}
}
}

Displays file icons in asp.net on GridView

I can't to display file icons according to file extensions in asp.net GridView.
The structure of GridView is nested
The tutorial is Displays file icons in asp.net
The error is :
Object reference not set to an instance of an object
In this line of code-behind :
if (!String.IsNullOrEmpty(lnkDownload.Text))
My code below.
Can you help me?
Thank you in advance for any help, really appreciated.
<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="mGrid" Width="700"
HorizontalAlign="Center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img id="fileImage" runat="server" src="" />
<asp:HiddenField ID="HiddenField1"
runat="server" Value='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download" ItemStyle-
HorizontalAlign="Justify">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text='<%#
Eval("Name") %>' CommandArgument=
'<%# Eval("FullName") %>' runat="server"
OnClick="lnkDownload_Click"
OnClientClick="if (!confirm('Confirm ?'))
return false;"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string root = #FilePath;
string folder = GridView2.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
Label gvLabel = (Label)e.Row.FindControl("gvLabel");
Label gvFolder = (Label)e.Row.FindControl("gvFolder");
DirectoryInfo directory = new DirectoryInfo(root + "/" + folder);
FileInfo[] fileInfo = directory.GetFiles("*.*",
SearchOption.AllDirectories);
fCount = directory.GetFiles("*.*",
SearchOption.AllDirectories).Length;
gvLabel.Text = fCount.ToString();
long size = 0;
foreach (string file in Directory.GetFiles(root + "/" + folder,
"*.*", SearchOption.AllDirectories))
{
size += new FileInfo(file).Length;
}
gvFolder.Text = Math.Round((double)size / (double)(1024 * 1024),
2).ToString() + " MB";
LinkButton lnkDownload =
(LinkButton)e.Row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)e.Row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
HtmlImage image = (HtmlImage)e.Row.FindControl("fileImage");
image.Attributes.Add("src", GetIconForFile(hf.Value));
}
gvOrders.DataSource = fileInfo;
gvOrders.DataBind();
}
}
private string GetIconForFile(string fileText)
{
string extension = Path.GetExtension(fileText);
extension = extension.Trim('.').ToLower();
return "~/fileicons/" + extension + ".png";
}
You have a Nested GridView Structure and gvOrders is your inner GridView. So, you've to get LinkButton from inner GridView's row as like:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvOrders = (GridView)e.Row.FindControl("gvOrders");
foreach (GridViewRow row in gvOrders.Rows)
{
LinkButton lnkDownload = (LinkButton)row.FindControl("lnkDownload");
HiddenField hf = (HiddenField)row.FindControl("HiddenField1");
if (!String.IsNullOrEmpty(lnkDownload.Text))
{
//... some code
}
}
}
}

how to fill dropdown in telerik grid databound?

i have a telerik grid and use GridTemplateColumn as bellow
<telerik:GridTemplateColumn DataField="Status" ReadOnly="true" UniqueName="colStatus" HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpstatus" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
then i fill dropdown and label in ItemDataBound event :
protected void grdList_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem editItem = (GridEditableItem)e.Item;
var info = (ProductViewInfo)e.Item.DataItem;
DropDownList drpstatus = (DropDownList)editItem["colStatus"].FindControl("drpstatus");
var cntType = new ProductTypeController();
var lst = cntType.GetStatusList(PortalId, enumTypes.MainGroup);
drpstatus.DataSource = lst;
drpstatus.DataTextField = "Caption";
drpstatus.DataValueField = "StatusID";
drpstatus.DataBind();
drpstatus.SelectedValue = info.Status.ToString();
}
else
{
var item = e.Item as GridDataItem;
var info = (ProductViewInfo)item.DataItem;
Label lblStatus = (Label)item["colStatus"].FindControl("lblStatus");
lblStatus.Text = info.StatusCaption;
}
}
}
but my drop down does not fill! "e.Item.IsInEditMode" always returns false. should i add anything else in order to fill dropdown?
I guess the problem related to ReadOnly="true"
try to remove it

Add new record to Telerik RadGrid

I have the following Telerik RadGrid, which I'm using in C#:
<MasterTableView Width="100%" EditMode= "InPlace" ClientDataKeyNames="menuID" CommandItemDisplay= "Top">
<Columns>
<telerik:GridBoundColumn DataField="Name" HeaderText="Name" SortExpression="Name" UniqueName="Name"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="Type" HeaderText="Type">
<ItemTemplate>
<asp:TextBox ID="Type" Text='<%# DataBinder.Eval(Container.DataItem, "Type") %>' runat="server"></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="List" HeaderText="List">
<ItemTemplate>
<asp:CheckBox ID="List" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "List") %>' />
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="loadAtStart" HeaderText="loadAtStart">
<ItemTemplate>
<asp:CheckBox ID="loadAtStart" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "loadAtStart") %>' />
</ItemTemplate>
<EditItemTemplate>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
The grid is populated with data, and working normally when editing the data.
But when I click on the Add New Record button provided by Telerik, then an empty row is added without any TextBox or CheckBox in the columns to edit in the new Row added. It's just an empty row. I presume that I have to create the controls dynamically in the called ItemDataBound event, but I didn't manage to find the actual code for this.
How do I solve this?
Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
AllowFilteringByColumn="true" AllowPaging="true" OnItemCommand="RadGrid1_ItemCommand">
<PagerStyle AlwaysVisible="true" />
<MasterTableView DataKeyNames="UniqueID" CommandItemDisplay="Top">
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Save All" OnClick="Button1_Click" />
ASPX.CS
public partial class aaaa : System.Web.UI.Page
{
public List<Employee> lstEmployee
{
get
{
if (Session["lstEmployee"] != null)
{
return (List<Employee>)Session["lstEmployee"];
}
else
{
return new List<Employee>();
}
}
set
{
Session["lstEmployee"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Employee> list = new List<Employee>();
Employee obj = new Employee();
obj.ID = 1;
obj.Name = "Name1";
obj.UniqueID = Guid.NewGuid();
list.Add(obj);
obj = new Employee();
obj.ID = 2;
obj.Name = "Name2";
obj.UniqueID = Guid.NewGuid();
list.Add(obj);
lstEmployee = list;
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = lstEmployee;
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.InitInsertCommandName)
{
saveAllData();
lstEmployee.Insert(0, new Employee() { UniqueID = Guid.NewGuid() });
e.Canceled = true;
RadGrid1.Rebind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
saveAllData();
}
protected void saveAllData()
{
//Update Session
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
Guid UniqueID = new Guid(item.GetDataKeyValue("UniqueID").ToString());
Employee emp = lstEmployee.Where(i => i.UniqueID == UniqueID).First();
emp.Name = (item.FindControl("TextBox1") as TextBox).Text;
}
}
}
public class Employee
{
public Guid UniqueID { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public int weeknumber { get; set; }
}
I have modified the parameters according to my requirement and also included all CURD operations.
ASPX Page
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="RadGrid1_NeedDataSource"
AllowFilteringByColumn="true" AllowPaging="true" OnItemCommand="RadGrid1_ItemCommand">
<PagerStyle AlwaysVisible="true" />
<MasterTableView DataKeyNames="UniqueID" CommandItemDisplay="Top" AutoGenerateColumns="false" >
<Columns>
<telerik:GridEditCommandColumn ButtonType="FontIconButton" />
<telerik:GridButtonColumn CommandName="Delete" Text="Delete" ButtonType="FontIconButton" UniqueName="DeleteColumn" />
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn DataField="Sku" UniqueName="Sku" HeaderText="Sku">
<ItemTemplate>
<asp:Label ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:TextBox>
</InsertItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Save All" OnClick="Button1_Click" />
<telerik:RadAjaxManager runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadGrid1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" />
<telerik:AjaxUpdatedControl ControlID="Button1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
</telerik:RadAjaxLoadingPanel>
CS Code
public List<ItemDetail> ItemDetail
{
get
{
if (Session["ItemDetail"] != null)
{
return (List<ItemDetail>)Session["ItemDetail"];
}
else
{
return new List<ItemDetail>();
}
}
set
{
Session["ItemDetail"] = value;
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = ItemDetail;
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.InitInsertCommandName)
{
}
if (e.CommandName == RadGrid.PerformInsertCommandName)
{
var item = (GridEditFormItem)e.Item;
var txtReferenceNumber = (TextBox)item.FindControl(id: "TxtSku");
var val = txtReferenceNumber.Text;
ItemDetail.Insert(0, new ItemDetail() { UniqueID = Guid.NewGuid(), Sku = val, ID = Convert.ToInt32(22) });
item.Edit = false;
RadGrid1.Rebind();
}
if (e.CommandName == RadGrid.UpdateCommandName)
{
var item = (GridEditFormItem)e.Item;
var txtReferenceNumber = (TextBox)item.FindControl(id: "TxtSku");
string requestId = item.GetDataKeyValue(keyName: "UniqueID").ToString().Trim();
Guid RequestIndentifier = Guid.Parse(requestId);
var val = txtReferenceNumber.Text;
var itemFind = ItemDetail.Where(x => x.UniqueID == RequestIndentifier);
itemFind.FirstOrDefault().Sku = val;
item.Edit = false;
RadGrid1.Rebind();
}
if (e.CommandName == RadGrid.DeleteCommandName)
{
var item = (GridDataItem)e.Item;
string requestId = item.GetDataKeyValue(keyName: "UniqueID").ToString().Trim();
Guid RequestIndentifier = Guid.Parse(requestId);
ItemDetail.RemoveAll(x => x.UniqueID == RequestIndentifier);
RadGrid1.Rebind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SaveAllData();
}
private void SaveAllData()
{
//Update Session
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
Guid UniqueID = new Guid(item.GetDataKeyValue("UniqueID").ToString());
ItemDetail emp = ItemDetail.Where(i => i.UniqueID == UniqueID).First();
emp.Sku = (item.FindControl("TxtSku") as TextBox).Text;
}
}
}
public class ItemDetail
{
public Guid UniqueID { get; set; }
public int ID { get; set; }
public string Sku { get; set; }
}
if (!Page.IsPostBack)
{
List<ItemDetail> list = new List<ItemDetail>();
ItemDetail obj = new ItemDetail
{
ID = 1,
Sku = "Name1",
UniqueID = Guid.NewGuid()
};
list.Add(obj);
obj = new ItemDetail();
obj.ID = 2;
obj.Sku = "Name2";
obj.UniqueID = Guid.NewGuid();
list.Add(obj);
ItemDetail = list;
}
Hope this would help you :-)
I'm not really a fan of any of these solutions because they require the use of Session. Session has it's place but I believe it's used more as a crutch.
You're already sending the RadGrid information back to the server-side via ViewState due to the PostBack so why not use it's information instead of relying on an in-memory store.
Example of Adding and Removing an item from a Grid. Yes, it does require iterating items to rebuild a List but it's an alternative to Session so I believe it has merit.
protected void addValueToRecentTagList(string text)
{
List<string> items = new List<string>();
foreach(GridDataItem row in RadGridNewTags.Items)
items.Add(row["tag"].Text);
items.Add(text);
RadGridNewTags.DataSource = items;
RadGridNewTags.DataBind();
}
protected void removeValueFromRecentTagList(string text)
{
List<string> items = new List<string>();
bool rebind = false;
foreach (GridDataItem row in RadGridNewTags.Items)
{
if (row["tag"].Text == text)
rebind = true;
else
items.Add(row["tag"].Text);
}
if (rebind)
{
RadGridNewTags.DataSource = items;
RadGridNewTags.DataBind();
}
}
You have to insert a control in the EditItemTemplate to display in Edit or Insert mode.
Or you can add an InsertItem Template and place a control in there:
<telerik:GridTemplateColumn UniqueName="loadAtStart" HeaderText="loadAtStart">
<ItemTemplate>
<asp:CheckBox ID="loadAtStart" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "loadAtStart") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="cbxEditLoadAtStart" runat="server" Checked='<%# Bind("loadAtStart") %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="cbxInsertLoadAtStart" runat="server" />
</InsertItemTemplate>
</telerik:GridTemplateColumn>

trigger for a button in a gridview in update panel

I have a gridview in an update panel and it is working fine. However on the click of the edit button I want to open the edit form. But the edit button click is not working. When i debug it, the method is working fine however the page doesn't postback. I have tried using triggers but to no avail.
<asp:UpdatePanel ID="upnlgrid" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:GridView ID="gvGroupMaster" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanging="gvGroupMaster_SelectedIndexChanging" OnSelectedIndexChanged="gvGroupMaster_SelectedIndexChanged" OnRowDataBound="gvGroupMaster_RowDataBound" AllowSorting="true" OnPageIndexChanging="gvGroupMaster_PageIndexChanging" OnSorting="gvGroupMaster_Sorting"
ShowHeader="True" CssClass="tabledata" Width="100%" DataKeyNames="igroup_id">
<AlternatingRowStyle CssClass="pointer" />
<RowStyle CssClass="even pointer" />
<HeaderStyle CssClass="headings" />
<Columns>
<asp:TemplateField HeaderText="Sort Order" ItemStyle-CssClass="colmn1" SortExpression="isort_position" >
<ItemTemplate>
<%-- <asp:ImageButton ID="btnSort" OnClick="btnSortClick" imageurl="../images/order-sort-btnup.png" runat="server"></asp:ImageButton>--%>
<asp:Button ID="btnSort" class="sortord pointer" runat="server" OnClick="btnSortClick" ></asp:Button>
<asp:Button ID="btnSortDown" class="sortorddown pointer" runat="server" OnClick="btnSortDownClick"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group Name" SortExpression="strgroup_name" ItemStyle-CssClass="colmn2" >
<ItemTemplate>
<asp:Label ID="lblGroupName" runat="server"
Text='<%# Bind("strgroup_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Short Name" SortExpression="strgroup_sname" ItemStyle-CssClass="colmn3" >
<ItemTemplate>
<asp:Label ID="lblShortName" runat="server"
Text='<%# Bind("strgroup_sname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Under" SortExpression="iparent_id" ItemStyle-CssClass="colmn4">
<ItemTemplate>
<asp:Label ID="lblUnder" runat="server"
Text='<%# Bind("strunder") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nature Of Group" SortExpression="strnature_of_group" ItemStyle-CssClass="colmn5">
<ItemTemplate>
<asp:Label ID="lblNatureOfGroup" runat="server"
Text='<%# Bind("strnature_of_group") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Affect Gross Profit" SortExpression="straffect_gross_profits" ItemStyle-CssClass="colmn6">
<ItemTemplate>
<asp:Label ID="lblAffectGrossProfits" runat="server" Text='<%# Bind("straffect_gross_profits") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nett DrCr Report" SortExpression="strnett_drcr_report" ItemStyle-CssClass="colmn7">
<ItemTemplate>
<asp:Label ID="lblNettDrcrReport" runat="server"
Text='<%# Bind("strnett_drcr_report") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created By" SortExpression="icreated_by" ItemStyle-CssClass="colmn8">
<ItemTemplate>
<asp:Label ID="lblCreatedBy" runat="server"
Text='<%# Bind("strcreated_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created On" SortExpression="dtcreated_on" ItemStyle-CssClass="colmn9">
<ItemTemplate>
<asp:Label ID="lblCreatedOn" runat="server"
Text='<%# Bind("dtcreated_on") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Updated On" SortExpression="dtupdated_on" ItemStyle-CssClass="colmn10">
<ItemTemplate>
<asp:Label ID="lbLastUpdatedOn" runat="server"
Text='<%# Bind("dtupdated_on") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions" ItemStyle-CssClass="colmn11">
<ItemTemplate>
<asp:Button id="btnInfo" runat="server" class="infoicon" Text='<%# Eval("igroup_id") %>' OnClick="infoclick"/>
<asp:Button id="btnEdit" runat="server" class="editicon" CausesValidation="false" Text='<%# Eval("igroup_id") %>' OnClick="editclick"/>
<asp:Button id="btnDelete" runat="server" class="deleteicon" Text='<%# Eval("igroup_id") %>' OnClick="deleteclick"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
codebehind for edit click
protected void editclick(object sender, EventArgs e)
{
try
{
//int rindex = (((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex;
Button EditButton = (Button)gvGroupMaster.Rows[(((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex].FindControl("btnEdit");
edit(EditButton.Text.ToString());
this.Session["edit"] = EditButton.Text.ToString();
}
catch
{
}
}
protected void edit(string editid)
{
try
{
GroupMasterClass gm = new GroupMasterClass();
CompanyMasterClass co = new CompanyMasterClass();
gm.igroup_id = Convert.ToInt32(editid);
ResultClass objres = gm.fn_GetGroupByIdForEdit();
if (objres.bStatus)
{
eslist<GroupMasterClass> OBJLIST = objres.objData as eslist<GroupMasterClass>;
if (OBJLIST.Count > 0)
{
co.strcompany_code = Request.Cookies["userinfo"]["companycode"].ToString();
ResultClass objress = co.fn_GetNameNumberStyle();
if (objress.bStatus)
{
eslist<CompanyMasterClass> OBJLISTS = objress.objData as eslist<CompanyMasterClass>;
if (OBJLISTS.Count > 0)
{
addfrm.Visible = true;
gridmain.Visible = false;
if (OBJLISTS[0].strname_style.ToString() == "PC")
{
txtGroupName.Text = misc.ToTitleCase(OBJLIST[0].strgroup_name);
txtGroupSname.Text = misc.ToTitleCase(OBJLIST[0].strgroup_sname);
}
if (OBJLISTS[0].strname_style.ToString() == "UC")
{
txtGroupName.Text = (OBJLIST[0].strgroup_name).ToUpper();
txtGroupSname.Text = (OBJLIST[0].strgroup_sname).ToUpper();
txtGroupName.Style.Add("text-transform", "uppercase");
txtGroupSname.Style.Add("text-transform", "uppercase");
}
if (OBJLISTS[0].strname_style.ToString() == "UG")
{
txtGroupName.Text = (OBJLIST[0].strgroup_name).ToUpper();
txtGroupSname.Text = (OBJLIST[0].strgroup_sname).ToUpper();
}
}
}
txtUnder.Text = OBJLIST[0].strunder;
txtNotes.Text = OBJLIST[0].strnotes;
for (int i = 0; i < OBJLIST.Count; i++)
{
CompanyMasterClass cm = new CompanyMasterClass();
string p = OBJLIST[0].strcompany_code.ToString();
string t = string.Empty;
string code = string.Empty;
int count = 0;
string[] availcompanycode = p.Split(',');
foreach (string k in availcompanycode)
{
t = k.ToString();
code += "'" + t.ToString() + "'" + ",";
count++;
}
cm.strcompany_code = code.TrimEnd(',');
ResultClass objrest = cm.fn_GetCompanyListByCompanycode();
if (objres.bStatus)
{
eslist<CompanyMasterClass> OBJLISTS = objrest.objData as eslist<CompanyMasterClass>;
if (OBJLISTS.Count > 0)
{
// listboxsource.Items.Clear();
listboxdestination.DataTextField = "strcompany_name";
listboxdestination.DataValueField = "strcompany_code";
listboxdestination.DataSource = OBJLISTS;
listboxdestination.DataBind();
}
}
ListItem itemnature = new ListItem();
if (OBJLIST[i].strnature_of_group == "A")
itemnature.Text = "Assets";
else if (OBJLIST[i].strnature_of_group == "E")
itemnature.Text = "Expenses";
else if (OBJLIST[i].strnature_of_group == "I")
itemnature.Text = "Income";
else if (OBJLIST[i].strnature_of_group == "L")
itemnature.Text = "Liabilities";
// itemnature.Value = OBJLIST[i].igroup_id.ToString();
ddlNature.Items.Add(itemnature);
ListItem itemaffects = new ListItem();
if (OBJLIST[i].straffect_gross_profits == "N")
itemaffects.Text = "No";
else if (OBJLIST[i].straffect_gross_profits == "Y")
itemaffects.Text = "Yes";
//itemaffects.Value = OBJLIST[i].igroup_id.ToString();
ddlGrossProfit.Items.Add(itemaffects);
ListItem itemnett = new ListItem();
if (OBJLIST[i].strnett_drcr_report == "N")
itemnett.Text = "No";
else if (OBJLIST[i].strnett_drcr_report == "Y")
itemnett.Text = "Yes";
// itemnett.Value = OBJLIST[i].igroup_id.ToString();
ddlNett.Items.Add(itemnett);
ListItem itemlock = new ListItem();
if (OBJLIST[i].strlock_status == "N")
itemlock.Text = "No";
else if (OBJLIST[i].strlock_status == "Y")
itemlock.Text = "Yes";
// itemnett.Value = OBJLIST[i].igroup_id.ToString();
ddlNett.Items.Add(itemlock);
}
}
}
}
catch
{
}
}
Any ideas?
Thanks,
Try using Button editbtn = (Button)sender; Rather than Button EditButton = (Button)gvGroupMaster.Rows[(((GridViewRow)(((Button)(sender)).Parent.BindingContainer))).RowIndex].FindControl("btnEdit");

Categories