How to transfer item from one datalist to other datalist? - c#

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();

Related

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
}
}
}
}

DataTable in ViewState is Returning Deleted Rows

I am currently working on a dynamic gridview that will allow a user to add or delete rows in order to be saved as database entries later on.
My gridview markup is as such:
<asp:UpdatePanel ID="upAirporterSchedule" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvAirporterSchedule" runat="server" ShowFooter="true" AutoGenerateColumns="false" CssClass="table table-striped table-bordered table-hover dataTable no-footer" OnRowDataBound="gvAirporterSchedule_RowDataBound" OnRowCommand="gvAirporterSchedule_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Location" ItemStyle-Width="25%">
<ItemTemplate>
<asp:DropDownList ID="ddlScheduleLoc" runat="server" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterStartDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("StartDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterEndDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("EndDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Departure Time">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterDepTime" runat="server" CssClass="form-control time-picker" Text='<%# Eval("DeptTimeColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-clock-o"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:TextBox ID="tbxAirporterDuration" runat="server" CssClass="form-control" Text='<%# Eval("DurationColumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" CssClass="btn btn-default" Text="Delete" CommandName="DeleteRow" />
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-default" Text="Add Entry" CommandName="AddRow" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Aside from this grid, I have some other fields in the user control. When I go to save, the user will click a button at the bottom of the user control which will package up the form fields above it and the grid into some classes and shoot this off to the database code to add/update this data.
Page.Validate("AirporterFares");
if (Page.IsValid)
{
try
{
// Save trip information.
SysVarService.SharedRideTrip trip = new SysVarService.SharedRideTrip();
if (_tripID > 0)
trip = Global.sysVarService.GetSharedRideTripByID(_tripID);
trip.isVisible = 1;
trip.productType = ReservationService.ProductType.TOUR;
trip.originStopID = Convert.ToInt32(ddlOrigin.SelectedValue.ToString());
trip.destinationStopID = Convert.ToInt32(ddlDestination.SelectedValue.ToString());
trip.defaultDuration = 0;
trip.effectiveDate = DateTime.Parse(tbxAirporterEffDate.Text.Trim());
trip.startTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
trip.endTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
// Save the two fare information.
SysVarService.SharedRideTrip_ShuttleFare aFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 1,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterAdultFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
SysVarService.SharedRideTrip_ShuttleFare cFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 2,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterChildFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
string status = "";
if (_updating)
status = Global.sysVarService.UpdateAirporterFare(trip, aFare, cFare, GetScheduleEntries());
else
status = Global.sysVarService.AddAirporterFare(trip, aFare, cFare, GetScheduleEntries());
if (!String.IsNullOrEmpty(status))
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = status;
return;
}
}
catch (Exception ex)
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = ex.ToString();
return;
}
Response.Redirect("~/Internal/Admin/Default.aspx?action=Airporter_Fares");
}
When I go to either add or update, I call GetScheduledEntries, which is supposed to loop through the datatable (grabbing it from the viewstate) and convert the templated fields into object properties and stuff these objects in a list.
private List<AdminConfigService.SharedRideTimes> GetScheduleEntries()
{
int idx = 0;
List<AdminConfigService.SharedRideTimes> schedule = new List<AdminConfigService.SharedRideTimes>();
if (gvAirporterSchedule.Rows.Count >= 1)
{
for (int i = 1; i <= gvAirporterSchedule.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
schedule.Add(new AdminConfigService.SharedRideTimes()
{
StartDate = DateTime.Parse(startDate.Text.Trim()),
EndDate = DateTime.Parse(endDate.Text.Trim()),
DepartureTime = DateTime.Parse(deptTime.Text.Trim()),
Duration = Convert.ToInt32(duration.Text.Trim()),
EffectiveDates = "",
StopID = Convert.ToInt32(ddl.SelectedValue.ToString())
});
idx++;
}
return schedule;
}
else
return schedule;
}
The problem is, if I delete rows from this grid view and then attempt to save the form, the datatable from the viewstate is bringing back those deleted rows and acting like they are still existing for saving, even though the gridview and the datatable do not have that row anymore (when the DeleteRow command goes through).
else if (e.CommandName == "DeleteRow")
{
SetRowData();
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int idx = gvr.RowIndex;
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[idx]);
currentRow = dt.NewRow();
ViewState["AirporterScheduleTable"] = dt;
gvAirporterSchedule.DataSource = dt;
gvAirporterSchedule.DataBind();
SetPreviousData();
}
}
}
private void SetPreviousData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
ddl.SelectedValue = dt.Rows[i]["LocColumn"].ToString();
startDate.Text = dt.Rows[i]["StartDateColumn"].ToString();
endDate.Text = dt.Rows[i]["EndDateColumn"].ToString();
deptTime.Text = dt.Rows[i]["DeptTimeColumn"].ToString();
duration.Text = dt.Rows[i]["DurationColumn"].ToString();
idx++;
}
}
}
}
private void SetRowData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable current = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
if (current.Rows.Count > 0)
{
for (int i = 1; i <= current.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
currentRow = current.NewRow();
current.Rows[i - 1]["LocColumn"] = ddl.SelectedValue;
current.Rows[i - 1]["StartDateColumn"] = startDate.Text;
current.Rows[i - 1]["EndDateColumn"] = endDate.Text;
current.Rows[i - 1]["DeptTimeColumn"] = deptTime.Text;
current.Rows[i - 1]["DurationColumn"] = duration.Text;
idx++;
}
ViewState["AirporterScheduleTable"] = current;
}
}
}
There doesn't seem to be any where in the code that I am not updating the ViewState datatable when I either delete or add entries to this dynamic gridview. What could be causing the difference in ViewStates? Does the full postback of the button outside of the UpdatePanel and GridView have a different ViewState?
I also pretty much followed this tutorial exactly.
Turned out to be one of those cases where you overlook something simple. When I was populating the grid with data on load, I did not protect it with a
if (!Page.IsPostback)
Because of that, every time the row was deleted, it would refill the data table with the data on Page Load and cause the weird issues where deleted rows didn't seem to be getting deleted.

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>

model binding webform TryUpdateModel not Working

I have a simple formview and simple modelbinding in webform:
<asp:FormView ID="frm" ItemType="SabaDoor2.Models.Content" SelectMethod="frm_GetItem" UpdateMethod="frm_UpdateItem" DataKeyNames="Id" runat="server">
<ItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>descripion :</label>
<asp:Label ID="lblDescription" Text='<%# Item.Description %>' runat="server"></asp:Label>
</p>
<p>
<asp:Button ID="btnEdit" Text="edit" CommandName="Edit" runat="server" />
</p>
</fieldset>
</ItemTemplate>
<EditItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>description :</label>
<asp:TextBox ID="txt" Text='<%# Item.Description %>' runat="server" ></asp:TextBox>
</p>
<p>
<asp:Button CommandName="Update" ValidationGroup="mainPropertyGroup" runat="server" ID="btnUpdate" Text="update" />
<asp:Button CommandName="Cancel" ValidationGroup="mainPropertyGroup" runat="server" ID="btnCancel" Text="cancel" />
</p>
</fieldset>
<br />
</EditItemTemplate>
</asp:FormView>
and in code:
Models.Model1Container _db = new Models.Model1Container();
protected void Page_Load(object sender, EventArgs e)
{
bindEvents();
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "";
if (!IsPostBack)
{
}
else
{
}
}
private void bindEvents()
{
frm.ItemUpdated += frm_ItemUpdated;
}
void frm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
if (e.Exception == null)
{
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "done!";
}
else
{
lblResult.ForeColor = System.Drawing.Color.Red;
lblResult.Text = "error:" + e.Exception.Message;
e.KeepInEditMode = true;
}
}
public SabaDoor2.Models.Content frm_GetItem([System.Web.ModelBinding.QueryString("Id")]int? Id)
{
return _db.Contents.Find(Id);
}
// The id parameter name should match the DataKeyNames value set on the control
public void frm_UpdateItem(int Id)
{
SabaDoor2.Models.Content item = null;
item = _db.Contents.Find(Id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", Id));
return;
}
var result = TryUpdateModel(item);
if (ModelState.IsValid)
{
_db.SaveChanges();
}
}
public override void Dispose()
{
_db.Dispose();
base.Dispose();
}
tryUpdateModel return true but my model(description field) doesn't update
:(
I find out logical error:
i have to initialize BindItem.Name property instd of item.Name
Text='<%# BindItem.Description %>'

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