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
}
}
}
}
Related
Kindly Look at the error screen. I just want to download file from template field in gridview I saving file in server directory and file path in db.
any with this fix or proper new solution
<asp:GridView ID="GridView1" runat="server"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("filepath") %>' runat="server" OnClick = "FilesDownload"></asp:LinkButton>
--%>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download"
Text='<%# Eval("Path") %>' CommandArgument='Eval("Path")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{ Response.Clear(); Response.ContentType = "application/octectstream";
Response.AppendHeader("content-disposition", "filename=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/File") + "//" + e.CommandArgument);
Response.End(); }
}
You need to follow the below steps:-
Add the TemplateField at the end as below.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("file") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and in Code-behind do something like this:-
protected void DownloadFile(object sender, EventArgs e)
{
try
{
string filePath = (sender as LinkButton).CommandArgument;
System.Net.WebClient req = new System.Net.WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath("~/YourFolder/" + filePath) + "\"");
byte[] data = req.DownloadData(Server.MapPath("~/YourFolder/" + filePath));
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
throw ex;
}
}
Reference link:- http://www.aspsnippets.com/Articles/Download-Files-from-GridView-using-LinkButton-Click-Event-in-ASPNet-using-C-and-VBNet.aspx
Hope that helps
I am working on resource files. I can now read resx file and get it populate the data into the grid-view. now here is my question now,
On a run time, i want to be able to edit the columns and also be able to click empty columns and click save to save my changes. How do i do that. please help me as i have tried many examples and it didn't work.
my code below,
private void btnNewfile_Click(object sender, EventArgs e)
{
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[] { oDataSet.Tables["data"].Rows[i][0].ToString(), oDataSet.Tables["data"].Rows[i][1].ToString(), font, datestamp, commentVal };
Gridview_Output.Rows.Add(row);
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(PathSelection);
}
Save button(the user must be able to save the file created or edit to any location (C drive))
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save Resource Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "resx";
saveFileDialog1.Filter = "Save Resource Files (*.resx)|*.resx";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//nere i need the user to save to any location he want not textbox.
txtOutputfile.Text = saveFileDialog1.FileName;
}
//oDataSet.Tables.Add("Data");
oDataSet.WriteXml(PathSelection);
versionIncrement();
MessageBox.Show("Successfully added ");
}
See if the below code helps.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="UpdateResource.aspx.cs" Inherits="UpdateResource" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Update Resource</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
//Enable Disable all TextBoxes when Header Row CheckBox is checked.
$("[id*=chkHeader]").bind("click", function () {
var chkHeader = $(this);
//Find and reference the GridView.
var grid = $(this).closest("table");
//Loop through the CheckBoxes in each Row.
$("td", grid).find("input[type=checkbox]").each(function () {
//If Header CheckBox is checked.
//Then check all CheckBoxes and enable the TextBoxes.
if (chkHeader.is(":checked")) {
$(this).attr("checked", "checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
} else {
$(this).removeAttr("checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
}
});
});
//Enable Disable TextBoxes in a Row when the Row CheckBox is checked.
$("[id*=chkRow]").bind("click", function () {
//Find and reference the GridView.
var grid = $(this).closest("table");
//Find and reference the Header CheckBox.
var chkHeader = $("[id*=chkHeader]", grid);
//If the CheckBox is Checked then enable the TextBoxes in thr Row.
if (!$(this).is(":checked")) {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
} else {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
}
//Enable Header Row CheckBox if all the Row CheckBoxes are checked and vice versa.
if ($("[id*=chkRow]", grid).length == $("[id*=chkRow]:checked", grid).length) {
chkHeader.attr("checked", "checked");
} else {
chkHeader.removeAttr("checked");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="cmbResources" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cmbResources_SelectedIndexChanged"
Width="275px">
</asp:DropDownList>
<br />
<br />
<asp:DataGrid ID="gridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
BorderColor="Black" BorderStyle="Groove" ForeColor="#333333" Width="500px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%= ++indexNum %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="English Word">
<ItemTemplate>
<%# DataBinder.Eval(Container,"DataItem.Key") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Translated Word">
<ItemTemplate>
<%--<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
BorderStyle="Groove" disabled="disabled"></asp:TextBox>--%>
<asp:TextBox ID="txtTrans" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
Enabled="false" BorderStyle="Groove"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<%--<asp:TemplateColumn>
<ItemTemplate>
<a href='editresource.aspx?key=<%# DataBinder.Eval(Container,"DataItem.Key") %>&file=<%=cmbResources.SelectedItem.Text %>&id=<%=indexNum - 1 %>'>
Edit</a>
</ItemTemplate>
</asp:TemplateColumn>--%>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<FooterStyle Font-Bold="True" ForeColor="White" />
<SelectedItemStyle Font-Bold="True" ForeColor="Navy" />
<PagerStyle ForeColor="#333333" HorizontalAlign="Center" />
<ItemStyle ForeColor="#333333" Font-Size="Small" Font-Names="verdana" />
<HeaderStyle Font-Bold="True" />
</asp:DataGrid>
<br />
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Xml;
public partial class UpdateResource : System.Web.UI.Page
{
public int indexNum = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//string resourcespath = Request.PhysicalApplicationPath + "App_GlobalResources";
//DirectoryInfo dirInfo = new DirectoryInfo(resourcespath);
//foreach (FileInfo filInfo in dirInfo.GetFiles())
//{
// string filename = filInfo.Name;
// cmbResources.Items.Add(filename);
//}
//cmbResources.Items.Insert(0, new ListItem("Select a Resource File"));
string[] filePaths = Directory.GetFiles(#"C:\Users\D1956\Desktop\ResourceEdit", "*.aspx");
foreach (string file in filePaths)
{
string[] f = file.Split(new char[] { '\\' });
cmbResources.Items.Add(f[f.Length - 1]);
}
}
}
protected void cmbResources_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbResources.SelectedIndex != 0)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
ResXResourceReader RrX = new ResXResourceReader(stream);
IDictionaryEnumerator RrEn = RrX.GetEnumerator();
SortedList slist = new SortedList();
while (RrEn.MoveNext())
{
slist.Add(RrEn.Key, RrEn.Value);
}
RrX.Close();
stream.Dispose();
gridView1.DataSource = slist;
gridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
string filename1 = filename.Remove(filename.Length - 5);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNodeList nlist = xmlDoc.GetElementsByTagName("data");
for (int i = 0; i < gridView1.Items.Count; i++)
{
CheckBox chkItem = (CheckBox)gridView1.Items[i].FindControl("chkRow");
if (chkItem.Checked)
{
XmlNode childnode = nlist.Item(i);
XmlNode lastnode = childnode.SelectSingleNode("value");
TextBox txtTran = (TextBox)gridView1.Items[i].FindControl("txtTrans");
lastnode.InnerText = txtTran.Text.ToString();
}
}
xmlDoc.Save(filename1 + "_1" + ".resx");
}
}
You may have to edit the !IsPostback part.
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>
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");
I have a datalist
<asp:DataList ID="dlstImage" runat="server" RepeatDirection="Horizontal" RepeatColumns="5"
CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" ImageUrl='<%#"~/Controls/ShowImage.ashx?FileName=" +DataBinder.Eval(Container.DataItem, "FilePath") %>'
OnCommand="Select_Command" CommandArgument='<%# Eval("Id").ToString() +";"+Eval("FilePath")+";"+Eval("Index") %>' /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
In which i am binding the image after uploading through uplodify upload, now i have one more datalist
and two btn up and down,
<asp:ImageButton ID="ibtnMoveUp" runat="server" ImageUrl="~/App_Themes/Default/Images/moveup.bmp"
Style="height: 16px" ToolTip="MoveUp The Item" />
<asp:ImageButton ID="ibtnMoveDown" runat="server" ImageUrl="~/App_Themes/Default/Images/movedown.bmp"
ToolTip="MoveDown The Item" />
<asp:DataList ID="dlstSelectedImages" runat="server" RepeatDirection="Horizontal"
RepeatColumns="5" CellSpacing="8">
<ItemTemplate>
<asp:ImageButton ID="Image" runat="server" /><br />
<asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%>
</ItemTemplate>
</asp:DataList>
My both datalist is in the same webuser control, datalist1 and datalist2 and I have 2 btn up and down, when i select one image from datalist1 and click on down btn then the selected image should move to datalist2. How to do that? someone please help me,
You need to handle the ItemCommand event of one DataList in which you have to copy the selected data (image) into another dataSource of two DataList and remove that item from the datasource of one DataList.
Markup:
<asp:DataList
ID="DataList1"
runat="server"
OnItemCommand="PerformMove"
>
<ItemTemplate>
<br /><%#Eval("Text") %>
<asp:Button ID="btn1"
runat="server"
Text="Move"
CommandName="cmd"
CommandArgument='<%#Eval("Text") %>'
/>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<br /><%#Eval("Text") %>
</ItemTemplate>
</asp:DataList>
Code-behind (.cs)
public class Data
{
public string Text { get; set; }
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list1 = new List<Data >()
{
new Data() { Text="One"},
new Data() { Text="Two"},
new Data() { Text="Three"},
};
List<Data> list2 = new List<Data>();
Session["list1"] = list1;
Session["list2"] = list2;
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
protected void PerformMove(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
List<Data> list1 = Session["list1"] as List<Data>;
List<Data> list2 = Session["list2"] as List<Data>;
list1.Remove(new Data() { Text=e.CommandArgument.ToString() });
list2.Add(new Data() { Text = e.CommandArgument.ToString() });
DataList1.DataSource = Session["list1"];
DataList1.DataBind();
DataList2.DataSource = Session["list2"];
DataList2.DataBind();
}
}
I am using this code and its working well for me.
ArrayList ImgArry = new ArrayList();
path = objGetBaseCase.GetImages(TotImgIds);
ImgArry.Add(SelImgId);
ImgArry.Add(SelImgpath);//image name
ImgArry.Add(SelImgName);//image path
//path.Remove(ImgArry);
List<ArrayList> t = new List<ArrayList>();
if (newpath.Count > 0)
t = newpath;
t.Add(ImgArry);
newpath = t;
for (int i = 0; i < newpath.Count; i++)
{
ArrayList alst = newpath[i];
newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstSelectedImages.DataSource = newtb;
DataBind();
path = objGetBaseCase.GetImages(TotImgIds);
for (int i = 0; i < path.Count; i++)
{
ArrayList alst = path[i];
tb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i);
}
dlstImage.DataSource = tb;
DataBind();