Sort Order Dropdown in Gridview - asp.net

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>

Related

DevExpress modify label in templateitem

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!!";

Telerik Radgrid row delete and restore the data on adding new row dynamically

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.

Cascading DropdownList in Gridview in ASP.NET

I am going to implement a cascading DropDownList inside a GridView control. My code is given below:
Page:
<asp:GridView ID="GridView1" runat="server" Width="550px"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1"
AutoPostBack="true" runat="server" DataTextField="State" DataValueField="StateID" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2"
AutoPostBack="true" runat="server" DataTextField="City" DataValueField="CityId">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Code Behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl1 = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl1 != null)
{
using (var context = new ABCEntities())
{
var _state= from u in context.State
select new
{
StateId= u.StateId,
State= u.State
};
ddl1.DataSource =_state.ToList();
ddl1.DataValueField = "StateId";
ddl1.DataTextField = "State";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList ddl1 = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl1.NamingContainer;
if (row != null)
{
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
ddl2.DataSource = GetDataForSecondDropDownList(Convert.ToInt32(ddl1.SelectedValue));
ddl2.DataTextField = "CityID";
ddl2.DataValueField = "City";
ddl2.DataBind();
}
}
public IEnumerable<City> GetDataForSecondDropDownList(int ID) //Getting Error
{
using (var context = new ABCEntities())
{
var _city = (from u in context.Cities
where u.StateID == ID
select new City
{
CityID = u.CityID,
City= u.City
}).Distinct();
return _city;
}
}
I am getting an error message : Error: Inconsistent accessibility: return type 'System.Collections.Generic.IEnumerable' is less accessible than method '.......GetDataForSecondDropDownList(int)'
what should i do please help me. Thanks in advance.
The error tells that City class is less accessible. Probably it is private or protected. Make sure you have declared it as public like this:
public class City
{
public int CityID {get;set;}
public string City {get;set;}
}

I have a gridview control populated from a database! I want to add a button with text property "reserve" at the end of each row of the 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.

Getting data from a checkbox inside a template column of asp.net gridview

This seems like something simple, but I can't seem to figure it out! I'm trying to get 2-way data-binding to work on an ASP.net page with a check box as one of the columns. How do I get the updated values (from check boxes) back from the gridview ?????
Here is my data type:
[Serializable]
public class UserRequirements
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public string Email { get; set; }
public bool ThingRequired { get; set; }
}
My markup looks something like this:
<form id="form1" method="post" runat="server" >
<asp:GridView ID="UserTable" runat="server" AutoGenerateColumns="false" >
<Columns>
...
<asp:TemplateField HeaderText="Required ?">
<ItemTemplate>
<asp:CheckBox id="chkBox1" runat="server" on
Text ="Required"
checked='<%# DataBinder.Eval(Container.DataItem,"ThingRequired") %>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button id="thebutton" Text="Save Changes" OnClick="UpdateRequirements" runat="server" CausesValidation=false />
</form>
My code behind looks something like this:
List<UserRequirements > _userList = new List<UserRequirements >();
protected void Page_Load(object sender, EventArgs e)
{
_userList = data_layer.GetUserRequirments();
this.UserTable.DataSource = _userList;
this.UserTable.DataBind();
}
Eventually, I will call something like this, but I don't know where this should go or how to get the values back from the gridview:
void UpdateRequirements(object sender, EventArgs e)
{
_userList = ???????????? // How do I get the data?
data_layer.UpdateUserRequirements( _userList );
}
foreach (GridViewRow di in GridView1.Rows)
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("chkBox1");
if (chkBx != null && chkBx.Checked)
{
/// put your code here
}
}
try something like this to get the value on change:
protected void OnCheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender as CheckBox;
string checkBoxId = c.ID;
bool checkBoxValue = c.Checked;
//update database
}
[EDIT]
If you want to get all the values from the rows in the grid in one go, you will need to bind the checkboxes using the Id for the row or item in your list of UserRequirements, so in your grid do something like this:
<asp:CheckBox ID="<%# Eval('Id') %>" />
then on postback, iterate through the items in the UserRequirements list matching the object/item Id with the Ids of the checkboxes in the grid .. something like this:
foreach (UserRequirement item in Requirements)
{
Control c = grid.FindControl(item.Id);
CheckBox cbx = c as CheckBox;
if (cbx != null)
{
bool value = cbx.Checked;
//update db
}
}
Note: you may need to use FindControl recursively to search child controls, or do a foreach on each GridViewRow object in the grid to pickup the checkbox you are looking for.

Resources