Getting the value of an edited item in a Telerik RadGrid - asp.net

ASPX:
<telerik:RadGrid ID="ctlItemsGrid" runat="server" DataKeyNames="Id" AllowPaging="true" AllowSorting="true" GridLines="None" Skin="Windows7" EnableViewState="true">
<MasterTableView AutoGenerateColumns="false" AllowPaging="true" DataKeyNames="Id,WorkflowStatus" NoMasterRecordsText="No items exist in the database." EnableViewState="true">
<SortExpressions>
<telerik:GridSortExpression FieldName="Id" SortOrder="Descending" />
</SortExpressions>
<PagerStyle Mode="NextPrevAndNumeric" />
<Columns>
<telerik:GridNumericColumn ColumnEditorID="ctlColumnId" HeaderText="ID" DataField="Id" DecimalDigits="0" DataType="System.Int32" NumericType="Number" ReadOnly="true"></telerik:GridNumericColumn>
<telerik:GridDropDownColumn UniqueName="ctlColumnGridWorkflow" ColumnEditorID="ctlColumnWorkflow" HeaderText="Workflow" DataField="WorkflowStatus" DropDownControlType="DropDownList"></telerik:GridDropDownColumn>
<telerik:GridEditCommandColumn UniqueName="ctlColumnGridEdit" CancelText="Cancel" EditText="Edit"></telerik:GridEditCommandColumn>
<telerik:GridButtonColumn UniqueName="ctlColumnGridDelete" CommandName="Delete" CommandArgument="" Text="Remove"></telerik:GridButtonColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
C#:
public partial class administration_modules_item_Default : ViewPageBase<IItemAdminPresenter, IItemAdminView>, IItemAdminView
{
private IEnumerable<WorkflowStatus> _workflowStatuses;
private IEnumerable<IItemDbItem> _items;
protected override void PreloadView()
{
this.ctlItemsGrid.ItemDataBound += new Telerik.Web.UI.GridItemEventHandler(ctlItemsGrid_ItemDataBound);
this.ctlItemsGrid.ItemCommand += new GridCommandEventHandler(ctlItemsGrid_ItemCommand);
//this.ctlItemsGrid.ItemUpdated += new GridUpdatedEventHandler(ctlItemsGrid_ItemUpdated);
this.ctlItemsGrid.UpdateCommand += new GridCommandEventHandler(ctlItemsGrid_UpdateCommand);
}
protected override void PostLoadView()
{
// Doesn't work, values are all empty strings
//foreach (GridEditableItem editItem in ctlItemsGrid.EditItems)
//{
// Dictionary<string, string> newValues = new Dictionary<string, string>();
// ctlItemsGrid.MasterTableView.ExtractValuesFromItem(newValues, editItem);
// IItemDbItem w = (IItemDbItem)editItem.DataItem;
// if (!string.IsNullOrWhiteSpace(newValues["WorkflowStatus"]))
// {
// w.WorkflowStatus = (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus), newValues["WorkflowStatus"]);
// this.Presenter.Update(w.Id, w.WorkflowStatus);
// }
//}
ctlItemsGrid.DataSource = _items;
ctlItemsGrid.DataBind();
base.PostLoadView();
}
void ctlItemsGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridEditableItem && (e.Item as GridEditableItem).IsInEditMode)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
// This doesn't work either, values are all null or empty:
//if (editedItem.CanExtractValues)
//{
// Dictionary<string, string> newValues = new Dictionary<string,string>();
// editedItem.ExtractValues(newValues);
// if (newValues["WorkflowStatus"] != null)
// {
// w.WorkflowStatus = (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus), newValues["WorkflowStatus"]);
// this.Presenter.Update(w.Id, w.WorkflowStatus);
// }
//}
GridDropDownListColumnEditor ctlColumnWorkflow = editMan.GetColumnEditor("ctlColumnGridWorkflow") as GridDropDownListColumnEditor;
ctlColumnWorkflow.DataSource = _workflowStatuses;
ctlColumnWorkflow.DataBind();
ctlColumnWorkflow.SelectedValue = w.WorkflowStatus.ToString();
}
else if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
dataItem["ctlColumnGridWorkflow"].Text = w.WorkflowStatus.ToString();
}
}
void ctlItemsGrid_ItemCommand(object sender, GridCommandEventArgs e)
{
string cmdName = e.CommandName;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
switch (cmdName)
{
case "Delete":
this.Presenter.Delete(w.Id);
this.Presenter.LoadView();
break;
case "Update":
// This doesn't work either:
//GridEditableItem editedItem = e.Item as GridEditableItem;
//GridEditManager editMan = editedItem.EditManager;
//DropDownList editWorkflow = (DropDownList)editedItem["ctlColumnGridWorkflow"].Controls[0];
//DropDownList editEvent = (DropDownList)editedItem["ctlColumnGridEvent"].Controls[0];
//this.Presenter.Update(w.Id, (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus));
break;
}
//this.Presenter.LoadView();
}
// Doesn't work:
//void ctlItemsGrid_ItemUpdated(object sender, GridUpdatedEventArgs e)
//{
// GridEditableItem editedItem = e.Item as GridEditableItem;
// GridEditManager editMan = editedItem.EditManager;
// DropDownList editWorkflow = editedItem["ctlColumnGridWorkflow"].Controls[0] as DropDownList;
// IItemDbItem w = (IItemDbItem)e.Item.DataItem;
// this.Presenter.Update(w.Id, (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus), editWorkflow.SelectedValue));
//}
// Doesn't work:
void ctlItemsGrid_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
DropDownList editWorkflow = editedItem["ctlColumnGridWorkflow"].Controls[0] as DropDownList;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
this.Presenter.Update(w.Id, (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus), editWorkflow.SelectedValue));
}
public IEnumerable<WorkflowStatus> WorkflowStatuses
{
set
{
_workflowStatuses = value;
}
}
public IEnumerable<IItemDbItem> Items
{
get
{
return _items;
}
set
{
_items = value;
}
}
}
I have a separate form to add items (not shown), that works fine. Also the Delete button works fine. When trying to update the saved item, all the values that I can get from the GridDropDownColumn are either null, empty, or the default values, not the edited values. When stepping through and testing things in the Immediate Window in Visual Studio, I was able to find the correct value using this ridiculous statement:
((DropDownList)ctlItemsGrid.MasterTableView.GetItems(GridItemType.EditFormItem)[0].Controls[1].Controls[0].Controls[0].Controls[1].Controls[0].Controls[0].Controls[1].Controls[1].Controls[0]).SelectedValue
But there has to be an easier way. What am I doing wrong?

Odd that the initial implementation didn't work - I cooked up a quick sample project on my end and managed to get the all the information from e.Item.DataItem (albeit only the Id column since we're binding to the DropDownList later).
Is there a strict requirement on grabbing this from the ItemDataBound event? A better event would be the UpdateCommand. You can easily get the item by using some quick code:
protected void ctlItemsGrid_UpdateCommand(object sender, GridCommandEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem item = e.Item as GridEditableItem;
string Employee = (item["ctlColumnGridWorkflow"].Controls[0] as DropDownList).SelectedItem.Text;
}
}
Then you can extract desired values using techniques discussed in this documentation article.
If you still want to approach it like in your first attempt a standalone sample project might be in order to see exactly what is going on.

I'm not sure if this was the right way to fix it, but this works for me:
public partial class administration_modules_item_Default : ViewPageBase<IItemAdminPresenter, IItemAdminView>, IItemAdminView
{
private IEnumerable<WorkflowStatus> _workflowStatuses;
private IEnumerable<IItemDbItem> _items;
protected override void PreloadView()
{
this.ctlItemsGrid.ItemDataBound += new Telerik.Web.UI.GridItemEventHandler(ctlItemsGrid_ItemDataBound);
this.ctlItemsGrid.ItemCommand += new GridCommandEventHandler(ctlItemsGrid_ItemCommand);
this.ctlItemsGrid.NeedDataSource += new GridNeedDataSourceEventHandler(ctlItemsGrid_NeedDataSource);
}
void ctlItemsGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
ctlItemsGrid.DataSource = _items;
}
protected override void PostLoadView()
{
if (!IsPostBack)
{
ctlItemWorkflow.DataSource = _workflowStatuses;
ctlItemWorkflow.DataBind();
}
base.PostLoadView();
}
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
ctlItemsGrid.Rebind();
}
void ctlItemsGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridEditableItem && (e.Item as GridEditableItem).IsInEditMode)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
GridDropDownListColumnEditor ctlColumnWorkflow = editMan.GetColumnEditor("ctlColumnGridWorkflow") as GridDropDownListColumnEditor;
ctlColumnWorkflow.DataSource = _workflowStatuses;
ctlColumnWorkflow.DataBind();
ctlColumnWorkflow.SelectedValue = w.WorkflowStatus.ToString();
}
else if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
dataItem["ctlColumnGridWorkflow"].Text = w.WorkflowStatus.ToString();
}
}
void ctlItemsGrid_ItemCommand(object sender, GridCommandEventArgs e)
{
string cmdName = e.CommandName;
IItemDbItem w = (IItemDbItem)e.Item.DataItem;
switch (cmdName)
{
case "Delete":
GridDataItem item = e.Item as GridDataItem;
int id = Convert.ToInt32(item.GetDataKeyValue("Id"));
this.Presenter.Delete(id);
this.Presenter.LoadView();
break;
case "Update":
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
DropDownList editWorkflow = (DropDownList)editedItem["ctlColumnGridWorkflow"].Controls[0];
int wid = Convert.ToInt32(editedItem.GetDataKeyValue("Id"));
this.Presenter.Update(wid, (WorkflowStatus)Enum.Parse(typeof(WorkflowStatus), editWorkflow.SelectedValue));
this.Presenter.LoadView();
break;
}
}
public IEnumerable<WorkflowStatus> WorkflowStatuses
{
set
{
_workflowStatuses = value;
}
}
public IEnumerable<IItemDbItem> Items
{
get
{
return _items;
}
set
{
_items = value;
}
}
}
Using the NeedDataSource and Rebind seemed to let the ItemCommand start functioning as expected.

Related

How to paint cells in row (Telerik)?

I've next code that handle fowFormatting my cells:
private void gridViewRaces_RowFormatting(object sender, RowFormattingEventArgs e)
{
foreach (var cellColumn in e.RowElement.Data.Cells)
{
var cellInfo = cellColumn as GridViewCellInfo;
if (cellInfo != null)
{
cellInfo.Style.DrawFill = true;
if (cellInfo.ColumnInfo.Name == "columnContactProducerName")
{
cellInfo.Style.DrawFill = true;
cellInfo.Style.BackColor = Color.Yellow;
}
else if (cellInfo.ColumnInfo.Name == "columnTransport")
{
cellInfo.Style.BackColor = Color.Yellow;
}
else
{
cellInfo.Style.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
}
}
//e.RowElement.BackColor = ColorTranslator.FromHtml((e.RowElement.Data.DataBoundItem as RaceForListDto).Color);
}
but my cells aren't painting. How to paint some cells in rows on dataBinding?
It looks like the proper event to do this is ItemDataBound event. See here:
http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/appearance-and-styling/conditional-formatting
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
//Is it a GridDataItem
if (e.Item is GridDataItem)
{
//Get the instance of the right type
GridDataItem dataBoundItem = e.Item as GridDataItem;
//Check the formatting condition
if (int.Parse(dataBoundItem["Size"].Text) > 100)
{
dataBoundItem["Received"].ForeColor = Color.Red;
dataBoundItem["Received"].Font.Bold = true;
//Customize more...
}
}
}
Or event better is to use a custom CSS class so that you can later make changes without having to rebuild the project:
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e){
if (e.Item is GridDataItem)
{
GridDataItem dataItem = e.Item as GridDataItem;
if (dataItem["Country"].Text == "Mexico")
dataItem.CssClass = "MyMexicoRowClass";
}
}

Duplicate columns get created while clicking "Edit" in asp:GridView

I have asp:GridView where I am using AutoGenerateEditButton="True" property to edit the grid row. Now the issue is whenever I click Edit button, the columns are populating again. For example If there 4 columns and if I click Edit than same 4 columns will reappear.
.ASPX Code:
<asp:GridView ID="grdEmpDetail" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowEditing="grdEmpDetail_RowEditing"
OnRowCancelingEdit="grdEmpDetail_RowCancelingEdit"
OnRowUpdated="grdEmpDetail_RowUpdated"
AutoGenerateEditButton="True">
</asp:GridView>
Code Behind: To Dynamically bind data on grid
protected void Page_Load(object sender, EventArgs e)
{
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch
{
throw;
}
}
Handle Edit Mode:
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
this.grdEmpDetail.DataBind();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
this.grdEmpDetail.DataBind();
}
OUTPUT: This is fine
ISSUE : This is where I am getting issue.
What am I missing here?
You are not checking for IsPostBack in your databinding code. As a result, each time you post to the page that code is being executed again and again. So each time you will add more columns.
Modify your handler like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
// All of your existing code goes here
}
}
Edit
It's a little more complicated than that. You DO actually need to re-bind your DataGrid to the data source when you click edit, but you just don't want to add the columns again. This requires that you break up your code some so that the code for data-binding can be re-used without being tied to the column addition.
First, let's create a method specifically for adding columns that appear on an input DataTable:
private void AddColumnsToDataGrid(DataTable dt) {
foreach (var col in dt.Columns) {
if (col.ToString() == "ID"
|| col.ToString() == "First Name"
|| col.ToString() == "Last Name"
|| col.ToString() == "Business Phone"
|| col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
}
Next Create a Method for Databinding a DataTable to your grid:
private void DataBindGrid(DataTable dt) {
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
Now that you've extracted some of that code out, you can re-use these methods where appropriate, and only add columns one time:
Page Load Handler
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try {
DataTable dt = objBL.OrderDetail();
AddColumnsToDataGrid(dt);
DataBindGrid(dt);
} catch {
// Side Note: If you're just re-throwing the exception
// then the try/catch block is completely useless.
throw;
}
}
}
Editing Handlers
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Grid();
}
}
protected Void Fill_Grid()
{
if (grdEmpDetail.Columns.Count > 0)
{
for (int n = 0; n < grdEmpDetail.Columns.Count; n++)
{
grdEmpDetail.Columns.RemoveAt(n);
}
grdEmpDetail.DataBind();
}
this.grdEmpDetail.AutoGenerateColumns = false;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch (exception e1)
{
}
}
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
Fill_Grid();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
Fill_Grid();
}

check if button is clicked in if() condition aspx.net

I want to check if btnTest_Click is clicked in another Button6_Click event.Below is my code.....Please help
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if()
}
as per Kevin's answer but instead of:
protected bool testPassed;
Have this:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
By accessing the value of this property via view state the value will persist between requests.
I would declare a class level boolean called testPassed.
Set it to false in the onload event if it is not a Postback.
Set it to true in the btnTest_Click event handler
Edit to add an example:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
testPassed=false;
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
testPassed=true;
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if(testPassed)
}

checkboxlist selectedindexchanged event c# not working

I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;

Asp.net GridView Enabling row selection

I am using GridView in asp.net. I want to select a single data row. I looked for MultiSelect and SelectionMode in property panel, but I can't find it.
So how to enable selecting rows in GridView?
Thanks.
Code Behind
public partial class SearchCourse : System.Web.UI.Page
{
Connection dbCon;
DataTable tbl;
protected void Page_Load(object sender, EventArgs e)
{
dbCon = new Connection();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked) {
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled =false;
txtSubName.Text = "";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) {
comboProgram.Enabled = true;
if (comboProgram.SelectedItem.ToString() == "Foundation Course")
{
comboSemester.Enabled = false;
comboYear.Enabled = false;
}
else {
comboSemester.Enabled = true;
comboYear.Enabled = true;
}
txtSubName.Text = "";
txtSubName.Enabled = false;
}
}
protected void imgBtnSearch_Click(object sender, ImageClickEventArgs e)
{
if (RadioButton1.Checked) {
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectName(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton2.Checked)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem= comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program,year,sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
else if (RadioButton3.Checked)
{
String name = txtSubName.Text;
tbl = dbCon.getResultsBySubjectNo(name);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year, sem;
if (program == "Foundation Course")
{
comboYear.Enabled = false;
comboSemester.Enabled = false;
year = null;
sem = null;
}
else {
comboYear.Enabled = true;
comboSemester.Enabled = true;
year = comboYear.SelectedItem.ToString();
sem = comboSemester.SelectedItem.ToString();
}
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboYear_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void comboSemester_SelectedIndexChanged(object sender, EventArgs e)
{
String program = comboProgram.SelectedItem.ToString();
String year = comboYear.SelectedItem.ToString();
String sem = comboSemester.SelectedItem.ToString();
tbl = dbCon.getResultsByProgram(program, year, sem);
GridView1.DataSource = tbl;
GridView1.DataBind();
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
txtSubName.Enabled = true;
comboSemester.Enabled = false;
comboYear.Enabled = false;
comboProgram.Enabled = false;
txtSubName.Text = "";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
GridView Code
<asp:GridView ID="GridView1" CssClass="grid" runat="server" AllowPaging="True"
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
GridLines="Horizontal" EnableViewState="False"
PageSize="5" onselectedindexchanged="GridView1_SelectedIndexChanged" >
<RowStyle CssClass="gridRow" Width="800px" />
<SelectedRowStyle BackColor="#FF0066" ForeColor="White" />
</asp:GridView>
I think the MultiSelect and SelectionMode properties are only available with the VB.NET grid, not in ASP.NET. Bear in mind that all controls in ASP.NET are HTML-in-disguise, so they may be more limited. There is no reason why you can't have a multi-select table, but you have to do the plumbing yourself. So you need to enable row selection, either by handling the RowDataBound event as in
http://forums.asp.net/t/992062.aspx?How+to+select+row+in+gridview+on+click
or else using the MS-provided option as in
http://msdn.microsoft.com/en-us/library/wbk82279(v=vs.100).aspx
Then you need to handle the SelectedIndexChanging event, figure out which row the user clicked on, and handle the row-colouring yourself.
This problem is still actual for me 9 years later.
In As?x code I added SelectedRowStyle and asp:CommandField blocks:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<SelectedRowStyle BackColor="#337ab7" ForeColor="White" />
<Columns>
<asp:CommandField SelectText="Select" ShowSelectButton="True">
<HeaderStyle Width="50px" />
</asp:CommandField>
Code behind:
protected void GridView1_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
}
In gridview you have to define an event onselectedindexchanged and onrowdatabound as below:
onselectedindexchanged="GridView1_SelectedIndexChanged" onrowdatabound="GridView1_RowDataBound"
to show the selected row you can use following style in your grid view:
<SelectedRowStyle BackColor="Red" />
in code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Set the hand mouse cursor for the selected row.
e.Row.Attributes.Add("OnMouseOver", "this.style.cursor = 'hand';");
// The seelctButton exists for ensuring the selection functionality
// and bind it with the appropriate event hanlder.
LinkButton selectButton = new LinkButton()
{
CommandName = "Select",
Text = e.Row.Cells[0].Text
};
selectButton.Font.Underline = false;
selectButton.ForeColor = Color.Black;
e.Row.Cells[0].Controls.Add(selectButton);
//e.Row.Attributes["OnClick"] =
// Page.ClientScript.GetPostBackClientHyperlink(selectButton, "");
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
note: you can find the event in event window.

Resources