how to fill dropdown in telerik grid databound? - c#

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

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

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

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

DataList loaded dynamically, how to store values inside between postbacks

I am loading a Datalist to create the necessary filters (textbox's,dropdown's,checkbox's) for a grid. So far so good, the problem is between postback's.
I understand that every time a postback occours I need to recreate the Datalist with the items, but how can I store the input made by the user on each control?
Imagine that I have created a textbox for filtering a column and the user input "test" on the textbox and click on button that triggers the event to search the value in the gridview.
How can I use (if so) the "viewstate" and when?
Here is the code
Client code:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="imgHelp" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnlFilter" runat="server" Width="95%">
<asp:DataList ID="dlFilter" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dlFilter_ItemDataBound" OnItemCreated="dlFilter_ItemCreated" EnableViewState="true">
<ItemTemplate>
<asp:HiddenField ID="hfFilterName" runat="server" Value='<%# Bind("szFilterName") %>' />
<asp:HiddenField ID="hfFilterType" runat="server" Value='<%# Bind("szFilterObjType") %>' />
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("szFilterFiller") %>' />
</ItemTemplate>
<FooterTemplate>
<table>
<tr>
<td valign="middle" style="width: 120px; text-align: right;">
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Font-Names="Verdana" Font-Size="7pt" OnClick="btnSubmit_Click"
Text="Search" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:DataList>
</asp:Panel>
<br />
<div id="div1" style="overflow: auto; height: auto; width: 97%;">
<asp:GridView ID="gv" runat="server" CssClass="tablecloth-theme" Width="97%" GridLines="Vertical"
AllowSorting="True" AllowPaging="True" PageSize="20" OnPageIndexChanging="gv_PageIndexChanging"
OnSorting="gv_Sorting" SelectedRowStyle-BackColor="Beige" OnSelectedIndexChanged="gv_SelectedIndexChanged">
<HeaderStyle BackColor="#7799AF" Font-Bold="True" Height="20px" Font-Names="Verdana"
Font-Size="7pt" ForeColor="White" HorizontalAlign="Left" />
<Columns>
<asp:CommandField SelectText="Details" ShowSelectButton="True" />
</Columns>
<AlternatingRowStyle BackColor="Gainsboro" />
<SelectedRowStyle BackColor="Beige" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (!scriptManager.IsInAsyncPostBack)
{
DataInfo_Load();
}
//Page_Prepare();
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected void DataInfo_Load()
{
try
{
DataSet_Load();
Filters_Load();
Grid_Load();
if ((int)ViewState["PageStatus"] >= 2)
{
if (ViewState["Saveable"] != null)
btnNew.Visible = (bool)ViewState["Saveable"];
else
btnNew.Visible = true;
}
else
btnNew.Visible = false;
}
catch (Exception ex)
{
throw ex;
}
}
protected void DataSet_Load()
{
try
{
Connection cn = new Connection();
DataSet ds = null;
string Query = hfSelStore.Value;
SqlCommand SQLcmd = new SqlCommand(Query);
SQLcmd.CommandType = System.Data.CommandType.StoredProcedure;
ds = cn.ExecuteSqlCmd(cn.SqlLocalConn, SQLcmd);
ViewState["DataSet"] = ds;
}
catch (Exception ex)
{
throw ex;
}
}
protected void Filters_Load()
{
try
{
if (ViewState["DataSet"] == null)
{
throw new Exception("No DataSet!");
}
DataSet ds = (DataSet)ViewState["DataSet"];
if (ds == null)
{
throw new Exception("DataSet is empty!");
}
if (ds.Tables.Count == 5)
{
//contains filter
pnlFilter.Visible = true;
DataView view = new DataView(ds.Tables[4]);
view.Sort = "lId";
dlFilter.DataSource = view;
dlFilter.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void dlFilter_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Retrieve the Label control in the current DataListItem.
HiddenField hfFilterName = (HiddenField)e.Item.FindControl("hfFilterName");
HiddenField filtertype = (HiddenField)e.Item.FindControl("hfFilterType");
if (filtertype != null)
{
DataListItem dlt = ((filtertype.Parent) as DataListItem);
int itemIndex = dlt.ItemIndex;
Label lbl = new Label();
lbl.ID = "lbl";
lbl.Text = hfFilterName.Value;
lbl.Attributes.Add("style", "font-size:7pt; color:#005780; font-weight:bold;");
Control ctr = Control_Create(filtertype.Value);
ctr.ID = "val";
dlt.Controls.Add(new LiteralControl("<table><tr><td valign=\"middle\" style=\"width: 120px; text-align: right;\">"));
dlt.Controls.Add(lbl);
dlt.Controls.Add(new LiteralControl("</td><td>"));
dlt.Controls.Add(ctr);
dlt.Controls.Add(new LiteralControl("</td></tr></table>"));
}
}
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected Control Control_Create(string controlType)
{
Control c = new TextBox();
try
{
if (controlType == "TextBox")
c = new TextBox();
else if (controlType == "CheckBox")
c = new CheckBox();
else if (controlType == "DropDownList")
c = new DropDownList();
else if (controlType == "RadioButton")
c = new RadioButton();
//else if (controlType == "Checkbox")
// c = new TextBox();
//else if (controlType == "Checkbox")
// c = new TextBox();
}
catch (Exception ex)
{
throw ex;
}
return c;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
gv.SelectedIndex = -1;
gv.PageIndex = 0;
Grid_Load();
}
catch (Exception ex)
{
ShowError(ex);
}
}
Can you help me out?
Thanks in advance!
First of all you do not need to load the listview on each postback. The ListView is able to hold the state information during the PostBack. However you should not call the DataBind() function on each postback, if you do so, it will loose the state information. Check where are you binding the ListView
Regarding the dynamic controls added to the ListView, if you add them in the ItemDataBound event as you are doing right now, they retain the state during postback if you call the DataBind() function during first page load i.e under
if(!IsPostBack) code block.
Another point is avoid creating the controls with html in the codebehind as much as possible. You can add these controls in the ItemTemplate and access them in the code behind. If you want to create multiple controls like a table under the list view, you can add a repeater control in the listview's ItemTemplate and bind the repeater in OnItemDataBound event of the ListView.
As I dont see your complete code like Control_Create function, I cannot assist or show code on how you can use Repeater control inside the ListView.

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>

How to transfer item from one datalist to other datalist?

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

Categories