I am working with DevExpress platform.
I have a axGridview that contains an ItemTemplate with a Label, i need just modify in every row with value.
With asp.net and GridView i used to manage FindControl in RowDataboundEvent, but here i really need help. The FindCellTemplate function always returns NULL.
here my code:
<dx:ASPxGridView ID="gvRecapiti" ClientIDMode="Static" ClientInstanceName="gvRecapiti" Width="100%" runat="server" AutoGenerateColumns="False"
OnHtmlRowCreated="gvRecapiti_HtmlRowCreated" >
<Columns>
<dx:GridViewDataColumn Caption="RecapitoTipo" >
<SettingsHeaderFilter>
<DateRangePickerSettings EditFormatString=""></DateRangePickerSettings>
</SettingsHeaderFilter>
</dx:GridViewDataColumn>
<dx:GridViewDataTextColumn FieldName="DescRecapito" >
<DataItemTemplate>
<dx:ASPxLabel ID="lblRecapito" ClientIDMode="Static" runat="server" ClientInstanceName="lblRecapito" Text='<%# Eval("DescRecapito") %>' ></dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
using DevExpress.Web;
namespace ProvaGridItem
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack != false)
{
BindGrid();
}
}
private void BindGrid()
{
List<Recapito> R = new List<Recapito>();
for (int i=0;i<5;i++)
{
Recapito Recapito = new Recapito();
Recapito.DescRecapito = "Recapito: " + i;
Recapito.RecapitoTipo="RecapitoTipo: "+i;
R.Add(Recapito);
}
gvRecapiti.DataSource = R;
gvRecapiti.DataBind();
}
protected void gvRecapiti_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
{
if (e.RowType != DevExpress.Web.GridViewRowType.Data) return;
ASPxLabel lblRecapitoTipo = (ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");
lblRecapitoTipo.Text = "Label Updated by code!!";
}
internal class Recapito
{
public string RecapitoTipo { get; set; }
public string DescRecapito { get; set; }
}
}
}
(ASPxLabel)gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, null, "lblRecapitoTipo");
This should have column to find control. so that first get column in a variable and then find template control of that column.Please go through with below code.
GridViewDataTextColumn col = gvRecapiti.Columns["lblRecapito"] as GridViewDataTextColumn;
ASPxLabel lblRecapitoTipo = gvRecapiti.FindRowCellTemplateControl(e.VisibleIndex, col , "lblRecapitoTipo") as ASPxLabel;
and then you can change lblRecapitoTipo label properties as you want.In your case it is
lblRecapitoTipo.Text = "Label Updated by code!!";
Related
My application consists of a web form that someone may be pulling some information in. When that occurs, I'm loading a user control more than once, based on content, that has an ImageButton on it.
Since this is being loaded after page is already loaded, how can I get the click events to work properly. Since click events are required to be set during page_load.
Example Scenario:
Main.aspx
<form id="form1" runat="server">
<div>
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</div>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
}
protected void ButClick(object sender, EventArgs e)
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
}
WFUC1.ascx
<asp:PlaceHolder runat="server" ID="DelAddrBtn"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public WFUC1()
{
TrashIcon = new ImageButton
{
AlternateText = "Delete Address",
ImageUrl = "/images/trash.png",
ToolTip = "Delete Address",
};
TrashIcon.Style.Add("cursor", "pointer");
TrashIcon.Style.Add("width", "24px");
}
private ImageButton TrashIcon { get; set; }
public int Ident { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
TrashIcon.ID = $"Delete_{Ident}";
TrashIcon.Click += new ImageClickEventHandler(this.TrashIcon_Click);
DelAddrBtn.Controls.Add(TrashIcon);
}
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
EDIT For Rango
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public partial class WFUC1 : System.Web.UI.UserControl
{
public int Ident { get; set; }
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
}
Seems, I have to reload all the controls on the main again to get the click event to execute. I accidentally made this work.
Below Project Visual Studio 2017 - No binaries, except for one image and the rest is only project code.
Main.aspx
<form id="form1" runat="server">
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
if(ViewState["ButClick"] != null)
LoadData();
}
protected void ButClick(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
ViewState["ButClick"] = true;
}
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<br />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
WFUC1.ascx
public int Ident { get; set; }
public void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
In my application I have a radschedular , when creating a new appointment I am opening in advance mode by specifying StartInsertingInAdvancedForm="True"
My code is given below
.aspx
<telerik:RadScheduler RenderMode="Lightweight" runat="server" ID="rs_course_schedule" CustomAttributeNames="Completed"
StartInsertingInAdvancedForm="True" StartEditingInAdvancedForm="True"
FirstDayOfWeek="Monday" LastDayOfWeek="Friday" Reminders-Enabled="true" SelectedView="WeekView"
RowHeight="30px" AppointmentStyleMode="Simple" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound"
OnAppointmentCommand="rs_course_schedule_OnAppointmentCommand"
OnAppointmentCreated="RadScheduler1_AppointmentCreated" OverflowBehavior="Auto" Skin="Web20"
OnAppointmentInsert="rs_course_schedule_OnAppointmentInsert">
<AdvancedForm Modal="true"></AdvancedForm>
<AppointmentTemplate>
<div class="appointmentHeader">
<asp:Panel ID="RecurrencePanel" CssClass="rsAptRecurrence" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="RecurrenceExceptionPanel" CssClass="rsAptRecurrenceException" runat="server"
Visible="false">
</asp:Panel>
<asp:Panel ID="ReminderPanel" CssClass="rsAptReminder" runat="server" Visible="false">
</asp:Panel>
<%#Eval("Subject") %>
</div>
<div>
Assigned to: <strong>
<asp:Label ID="UserLabel" runat="server" Text='<%# Container.Appointment.Resources.GetResourceByType("Faculty") == null ? "None" : Container.Appointment.Resources.GetResourceByType("Faculty").Text %>'></asp:Label>
</strong>
<br />
<asp:CheckBox ID="CompletedStatusCheckBox" runat="server" Text="Completed? " TextAlign="Left"
Checked='<%# !String.IsNullOrEmpty(Container.Appointment.Attributes["Completed"]) && Boolean.Parse(Container.Appointment.Attributes["Completed"]) %>'
AutoPostBack="true" OnCheckedChanged="CompletedStatusCheckBox_CheckedChanged"></asp:CheckBox>
</div>
</AppointmentTemplate>
<ResourceStyles>
<telerik:ResourceStyleMapping Type="Faculty" Key="1" BackColor="red"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="2" BackColor="Pink"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="3" BackColor="OrangeRed"></telerik:ResourceStyleMapping>
</ResourceStyles>
</telerik:RadScheduler>
in code behind
public partial class Schedule : System.Web.UI.UserControl
{
#region Object Instantiation
readonly BEL_LMS _objLms = new BEL_LMS();
readonly BL_LMS _blLms = new BL_LMS();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateSchedular();
AddTeachers();
SetDate();
}
}
private void AddTeachers()
{
_objLms.ActivityId = Session["activity_id"].ToString();
DataTable dtFaculty = _blLms.AssignedFaculty(_objLms);
ResourceType resources = new ResourceType("Faculty");
if (dtFaculty.Rows.Count > 0)
{
resources.DataSource = dtFaculty;
resources.KeyField = "userid";
resources.TextField = "acct_name";
resources.ForeignKeyField = "UserId";
rs_course_schedule.ResourceTypes.Add(resources);
}
}
private void SetDate()
{
rs_course_schedule.SelectedDate = DateTime.Now;
}
private void PopulateSchedular()
{
_objLms.Flag = "fetch";
_objLms.ActivityId = "11";
DataTable dtTable = _blLms.FetchScheduleForCourse(_objLms);
if (dtTable.Rows.Count > 0)
{
rs_course_schedule.DataKeyField = "ID";
rs_course_schedule.DataStartField = "Start";
rs_course_schedule.DataEndField = "End";
rs_course_schedule.DataSubjectField = "Subject";
rs_course_schedule.DataDescriptionField = "Description";
//rs_course_schedule.DataReminderField = "Reminder";
rs_course_schedule.DataSource = dtTable;
rs_course_schedule.DataBind();
}
}
protected void CompletedStatusCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox CompletedStatusCheckBox = (CheckBox)sender;
//Find the appointment object to directly interact with it
SchedulerAppointmentContainer appContainer = (SchedulerAppointmentContainer)CompletedStatusCheckBox.Parent;
Appointment appointment = appContainer.Appointment;
_objLms.ActivityId = appointment.ID.ToString();
_objLms.Flag = "update";
int affectedRow = _blLms.UpdateCourse(_objLms); // update checkbox data for that particular schedule
rs_course_schedule.Rebind();
}
protected void RadScheduler1_AppointmentDataBound(object sender, SchedulerEventArgs e)
{
if (e.Appointment.Attributes["Completed"] == "True")
{
e.Appointment.BackColor = System.Drawing.Color.Red;
}
}
protected void RadScheduler1_AppointmentCreated(object sender, AppointmentCreatedEventArgs e)
{
}
protected void rs_course_schedule_OnAppointmentInsert(object sender, AppointmentInsertEventArgs e)
{
SchedulerDataSource.InsertParameters["End"].DefaultValue = e.Appointment.End.ToString();
SchedulerDataSource.InsertParameters["Start"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Subject"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Description"].DefaultValue = e.Appointment.Description;
SchedulerDataSource.InsertParameters["CourseID"].DefaultValue = "1";
//SchedulerDataSource.InsertParameters["User"].DefaultVal;
}
protected void rs_course_schedule_OnAppointmentCommand(object sender, AppointmentCommandEventArgs e)
{
string name = e.CommandName;
}
}
}
Now when I am trying to insert a new appointment this form is opening
But in Save and Cancel button click is not occurring..
How I can solve this issue ?
I've the below code working just to display the radgrid headers with a button "Add new Course". Initially on page load I have no data to bind to radgrid. On "Add new Course" button click I add a new row to the RadGrid with 2 textboxes and 2 dropdownlist(binded from db). Each row should have "remove row' button. I've these working. Now my issue is I need to restore the data that has been entered by user when the user is trying to add another new row to the grid. And also how do I remove the row? Kindly help me by your suggestions or hightlight me the mistake in my existing code. thanks in advance.
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" MasterTableView-CommandItemSettings-ShowAddNewRecordButton="false" MasterTableView-CommandItemSettings-ShowRefreshButton="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnItemDataBound="RadGrid1_ItemDataBound" OnItemCommand="RadGrid1_ItemCommand">
<MasterTableView Width="100%" HeaderStyle-Font-Bold="true" CommandItemStyle-Font-Bold="true" DataKeyNames="IsAdd,BusID" CommandItemDisplay="Top" CommandItemStyle-HorizontalAlign="Right">
<CommandItemTemplate>
<asp:Button ID="IsAdd" Font-Size="Small" Font-Bold="true" CommandName="InitInsert" Text ="Add New Bus" runat="server" />
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn UniqueName="BusID" HeaderText="Bus #" DataField="BusID">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="Name" HeaderText="Bus Series" DataField="Name">
<ItemTemplate>
<asp:DropDownList ID="SeriesDropDown" DataTextField="SeriesName" runat="server" AutoPostBack="false"></asp:DropDownList>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="Name" HeaderText="Bus Group" DataField="Name">
<ItemTemplate>
<asp:DropDownList ID="GroupDropDown" DataTextField="GroupName" runat="server" AutoPostBack="false"></asp:DropDownList>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="Name" HeaderText="VIN" DataField="Name">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Remove Row" CommandName="Delete" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="savebtn" runat="server" Font-Bold="true" Text="Save Rows"/>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (!IsPostBack)
{
dt.Columns.Add("BusID");
dt.Columns.Add("Name");
dt.Columns.Add("IsAdd");
dt.Rows.Add(1, "Name1", false);
dt.Rows.Add(2, "Name2", false);
dt.Rows.Add(3, "Name3", false);
Session["dt"] = dt;
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = (DataTable)Session["dt"];
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
Button btn = new Button();
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
TextBox TextBox1 = item.FindControl("TextBox1") as TextBox;
Button Button1 = item.FindControl("Button1") as Button;
DropDownList SeriesDropDown = item.FindControl("SeriesDropDown") as DropDownList;
DropDownList GroupDropDown = item.FindControl("GroupDropDown") as DropDownList;
TextBox TextBox4 = item.FindControl("TextBox4") as TextBox;
DataSet busGroup_Dataset = admin.GetBusGroup();
GroupDropDown.DataSource = busGroup_Dataset;
GroupDropDown.DataBind();
DataSet busSeries_Dataset = admin.GetBusSeries();
SeriesDropDown.DataSource = busSeries_Dataset;
SeriesDropDown.DataBind();
bool isAdd = Convert.ToBoolean(item.GetDataKeyValue("IsAdd"));
if (isAdd)
{
TextBox1.Visible = SeriesDropDown.Visible = GroupDropDown.Visible = TextBox4.Visible = true;
btn.Visible = true;
RadGrid1.DataSource = Session["dt"];
}
else
{
TextBox1.Visible = SeriesDropDown.Visible = GroupDropDown.Visible = TextBox4.Visible = false;
Button1.Visible = false;
}
}
}
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.InitInsertCommandName)
{
DataTable dt = (DataTable)Session["dt"];
dt.Rows.Add(0, string.Empty, true);
RadGrid1.MasterTableView.IsItemInserted = false;
e.Canceled = true;
RadGrid1.Rebind();
}
if (e.CommandName == "Delete")
{
string ID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["0"].ToString();
DataTable table = (DataTable)Session["dt"];
if (table.Rows.Find(ID) != null)
{
table.Rows.Find(ID).Delete();
table.AcceptChanges();
Session["dt"] = table;
}
RadGrid1.Rebind();
}
}
Telerik RadGrid provides rich server API for inserting new data,
updating existing data and deleting data.
As telerik admin told you on official forum read the doc as i told you to do so 8 day earlier.
See the magic in action in the demo , learn more about it in the doc :
Please look at the telerik asp demo about DATA EDITING.
There is so mutch information about Data Editing
Let me do it for you !
The following exemple where developped in a new/clean telerik project you can just copy past them to try.
1/. With Advance binding Aka onNeedDataSource
In ASPX :
<telerik:RadGrid ID="RadGrid1"runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource"
GroupingEnabled="False"
AutoGenerateColumns="False"
OnInsertCommand="RadGrid1_InsertCommand"
AllowSorting="True"
AllowPaging="True">
<MasterTableView CommandItemDisplay="Top" EditMode="Batch" >
<CommandItemSettings ShowExportToPdfButton="false" ShowExportToExcelButton="false" ShowPrintButton="false" />
<Columns>
<telerik:GridBoundColumn UniqueName="CourseID" HeaderText="CourseID" DataField="CourseID" DataType="System.Int32" >
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="CourseNumber" HeaderText="CourseNumber" DataField="CourseNumber" DataType="System.Int32">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Location" HeaderText="Location" DataField="Location" DataType="System.String" >
</telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="Name" DataType="System.String" >
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
In CodeBehind :
public ObjectContainer myDatasource
{
get
{
if (Session["test_01"] == null)
Session["test_01"] = new ObjectContainer();
return Session["test_01"] as ObjectContainer ;
}
set { Session["test_01"] = value; }
}
protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
{
YoData row = new YoData();
ObjectContainer tempo = new ObjectContainer();
GridBatchEditingEventArgument argument = e.CommandArgument as GridBatchEditingEventArgument;
Hashtable newValues = argument.NewValues;
row.CourseID = Int32.Parse(newValues["CourseID"].ToString());
row.CourseNumber = Int32.Parse(newValues["CourseNumber"].ToString());
row.Location = newValues["Location"].ToString();
row.Name = newValues["Name"].ToString();
myDatasource.YoDatas.Add(row);
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
if ( ! IsPostBack )
{
for (int i = 0; i <= 8; i++)
{
YoData row = new YoData();
row.CourseID = i + 1;
row.CourseNumber = i + 1;
row.Name = "Name " + (i + 1);
row.Location = "Country " + (i + 1);
myDatasource.YoDatas.Add(row);
}
}
RadGrid1.DataSource = myDatasource.YoDatas;
}
In App_Code:
Im using object instead of DataTable, because it's easier.
namespace Demo
{
public class ObjectContainer
{
public ObservableCollection<YoData> YoDatas;
public ObjectContainer()
{
YoDatas = new ObservableCollection<YoData>();
}
public ObservableCollection<YoData> get_yoda(int mode = 0)
{
return this.YoDatas;
}
public void set_yoda(int CourseID, int CourseNumber, string Location, string Name)
{
YoData _temp = new YoData(CourseID, CourseNumber, Location, Name);
this.YoDatas.Add(_temp);
}
}
public class YoData
{
public int CourseID { get; set; }
public int CourseNumber { get; set; }
public DateTime CourseDate { get; set; }
public String Location { get; set; }
public String Name { get; set; }
public YoData()
{
CourseID = 0;
CourseNumber = 0;
CourseDate = DateTime.Now;
Location = "";
Name = "";
}
public YoData(int a, int b, DateTime c, string d, string e)
{
CourseID = a;
CourseNumber = b;
CourseDate = c;
Location = d;
Name = e;
}
public YoData(int a, int b, string d, string e)
{
CourseID = a;
CourseNumber = b;
CourseDate = DateTime.Now;
Location = d;
Name = e;
}
}
}
2/. in automatics, telerik do it for ya ( Later )
[edit comming soon....]
This is not the best solution, there must be some mistake in the code but it works. This is done with only the doc.
I hope this helps,
Regards,
Pierre.
I have a Gridview control with two columns: One is ID (a label) and the other is Sort Order (dropdown list). The dropdown is numbered from 1 to n, where n is the number of rows in the Gridview.
For example:
ID Sort Order
001 1
002 2
003 3
004 4
After I change the value in the dropdown list for one of the rows - for example, I'll change the Sort Order dropdown for ID 002 from 2 to 3 - the gridview should be updated like this:
ID Sort Order
001 1
003 2
002 3
004 4
I need the logic to accomplish this within the SelectedIndexChanged event for the dropdown, as well as the code to perform the update to the database.
If i correctly understood your problem then find solution of your problem as below :
Code Behind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList objDropDownList = e.Row.FindControl("DropDownList1") as DropDownList;
objDropDownList.DataSource = CustomSorting.GetAll();
objDropDownList.DataTextField = "SOText";
objDropDownList.DataValueField = "SOID";
objDropDownList.DataBind();
HiddenField objHiddenField = e.Row.FindControl("HiddenField1") as HiddenField;
string currSortOrder = (!string.IsNullOrEmpty(objHiddenField.Value) ? objHiddenField.Value :
"0");
objDropDownList.SelectedIndex = objDropDownList.Items.IndexOf(objDropDownList.Items.FindByValue(currSortOrder));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList objDropDownList = sender as DropDownList;
string test = objDropDownList.SelectedValue;
GridViewRow currRow = objDropDownList.NamingContainer as GridViewRow;
Label objLabel = currRow.FindControl("Label1") as Label;
HiddenField objHiddenField = currRow.FindControl("HiddenField1") as HiddenField;
List<TestClass> lstTestClass = PageData;
if (lstTestClass.Exists(x => x.SortOrder == Convert.ToInt32(test)))
lstTestClass.Find(x => x.SortOrder == Convert.ToInt32(test)).SortOrder =
Convert.ToInt32(objHiddenField.Value);
if (lstTestClass.Exists(x => x.ID == objLabel.Text))
lstTestClass.Find(x => x.ID == objLabel.Text).SortOrder = Convert.ToInt32(test);
PageData = lstTestClass;
BindGrid();
}
protected List<TestClass> PageData
{
get
{
return (Session["_PageData"] == null) ? TestClass.GetAll() : Session["_PageData"] as List<TestClass>;
}
set
{
Session["_PageData"] = value;
}
}
protected void BindGrid()
{
GridView1.DataSource = PageData.OrderBy(x=>x.SortOrder);
GridView1.DataBind();
}
}
public class CustomSorting
{
public int SOID { get; set; }
public string SOText { get; set; }
public static List<CustomSorting> GetAll()
{
return new List<CustomSorting>(){
new CustomSorting(){SOID=1,SOText="1"},
new CustomSorting(){SOID=2,SOText="2"},
new CustomSorting(){SOID=3,SOText="3"},
new CustomSorting(){SOID=4,SOText="4"},
};
}
}
public class TestClass
{
public string ID { get; set; }
public int SortOrder { get; set; }
public static List<TestClass> GetAll()
{
return new List<TestClass>(){
new TestClass(){ID="001",SortOrder=1},
new TestClass(){ID="002",SortOrder=2},
new TestClass(){ID="003",SortOrder=3},
new TestClass(){ID="004",SortOrder=4}
}.OrderBy(x=>x.SortOrder).ToList();
}
}
ASPX changes:
<asp:GridView ID="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sort Order">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("SortOrder") %>' />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Depending on whichh button is pressed I have to take the excursion_date_id which I will need in the next form!
SO what is best to use - buttonfield property maybe!
here is my code
First it's the Dates.class
public class Dates
{
private int excursionID;
private DateTime startdates;
private double prices;
public int ExcursionID
{
get { return excursionID; }
set { excursionID = value; }
}
public DateTime StartDates
{
get { return startdates; }
set { startdates = value; }
}
public double Prices
{
get { return prices; }
set { prices = value; }
}
public Dates()
{ }
}
}
Then I populate the gridview with the dates from my database
I want to have a button with text property "reserve" at the end of each row of the gridview!
protected void Page_Load(object sender, EventArgs e)
{
string excursionnId = Request.QueryString["ExcursionId"];
Dates date = new Dates();
List<Dates> listDate = new List<Dates>();
listDate = GetDates();
gvDates.DataSource = listDate;
gvDates.DataBind();
}
public List<Dates> GetDates()
{
List<Dates> datesList = new List<Dates>();
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string excursionnID = Request.QueryString["ExcursionID"];
string query =
"SELECT Excursion_date_ID, Excursion_ID, Start_date, Price FROM EXCURSION_DATES WHERE EXCURSION_ID='" + excursionnID + "'";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s=0;
while (rd.Read())
{
Dates dates = new Dates();
dates.ExcursionID = Convert.ToInt32(rd["Excursion_ID"]);
dates.StartDates = Convert.ToDateTime(rd["Start_date"]);
dates.Prices = Convert.ToDouble(rd["Price"]);
datesList.Add(dates);
}
}
catch (Exception EX)
{
}
return datesList;
}
}
<asp:GridView ID="gvDates" runat="server" Width="100%" AutoGenerateColumns="false"
OnRowCommand="grd_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" CausesValidation="false" CommandName="YourCommandName"
CommandArgument='<%#Eval("Excursion_ID") %>' runat="server" Text="Text" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
string number = (string)e.CommandArgument;
if (number==null) return;
switch (e.CommandName)
{
case "YourCommandName":
Load(number);
break;
// some others command
}
}
OR without rowcommand
<asp:GridView ID="gvDates" runat="server" Width="100%" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" CausesValidation="false" OnClick="btnClick"
CommandArgument='<%#Eval("Excursion_ID") %>' runat="server" Text="Text" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnClick(object sender, EventArgs e)
{
Button btn=(Button)sender;
if(btn==null) return;
string number = (string)btn.CommandArgument;
if (number==null) return;
Load(number);
}
In your .aspx page, specify the id of the GridView button to the ExcursionID. You can use buttonfield or place a button in a template column for that.