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