Disable gridview on checkboxlist selected value - c#

I have a Checkboxlist in which Items are binded from database.
Now what I want is, whenever user checks Registration / Conveyance Deed value from the list, Then the gridview should get disabled.
I tried with below code.
protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlStatus.SelectedValue == "30" && strMode == "M")
{
GridExpInfo.AllowAddingRecords = false;
}
else
{
GridExpInfo.AllowAddingRecords = true;
}
}
What happens is, it always shows the selected value of Agreement from the list, which is 20
Below is the screenshot of the list
update
ASPX:-
<asp:CheckBoxList ID="ddlStatus" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged">
</asp:CheckBoxList>
C#
private void BindStatus()
{
DataTable dtstatus = new DataTable();
OracleDataAdapter dastatus = new OracleDataAdapter("SELECT lookup_code agr_type_code, meaning agr_type " +
"FROM apps.fnd_lookup_values_vl " +
"WHERE (NVL ('', territory_code) = territory_code OR territory_code IS NULL " +
") AND lookup_type = 'XXACL_FARM_AGR_TYPE' " +
"AND (lookup_type LIKE 'XXACL_FARM_AGR_TYPE') " +
"AND (view_application_id = 0) " +
"AND (security_group_id = 0) " +
"ORDER BY 1", ObjPriCon);
dastatus.Fill(dtstatus);
ddlStatus.DataTextField = "agr_type";
ddlStatus.DataValueField = "agr_type_code";
ddlStatus.DataSource = dtstatus;
ddlStatus.DataBind();
}

You can set property AllowUserToAddRows to false inside code as shown below.
this.yourGrid.AllowUserToAddRows = false;
this.BindDataGridView();
And use ForEach loop for checking your condition. Now you check all selected items not only first selected.
protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem li in ddlStatus.Items)
{
if (li.Value == "30" && strMode == "M")
{
GridExpInfo.AllowUserToAddRows = false;
}
else
{
GridExpInfo.AllowUserToAddRows = true;
}
}
You can also use LINQ for checking it.
protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (strMode == "M")
{
var disable = (from ListItem item in ddlStatus.Items.OfType<ListItem>()
where item.Selected
where item.Value == "30"
select int.Parse(item.Value)).Any();
if (disable)
{
GridExpInfo.AllowUserToAddRows = false;
}
else
{
GridExpInfo.AllowUserToAddRows = true;
}
}
}

Try this snippet
protected void myCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
{
bool enableGrid = true;
foreach (ListItem listItem in ddlStatus.Items)
{
if (listItem.Value == "30" && listItem.Selected == true)
{
enableGrid = false;
}
}
if (enableGrid == true)
{
//enable grid and/or row inserts here
Label1.Text = "enabled";
}
else
{
//disable grid and/or row inserts here
Label1.Text = "disabled";
}
}

Related

Telerik: Unable to get Selected Value of Dropdownlist added to Autogenerated Radgrid

I added a dropdownlist to an auto-generated RadGrid in code behind, however, I am unable to get the selected value when the row is updated. I add the dropdownlist as follows:
protected void grdAssetImport_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem edit = (GridEditableItem)e.Item;
TextBox txt = (TextBox)edit["AssetTypeName"].Controls[0];
txt.Visible = false;
DropDownList rddl = new DropDownList();
PortalView.LookupListBO list = LookupListBA.LookupList_GetByKey(DB_Context, "SITE_ASSETTYPE_LIST", UtilityBA.IsActiveChoice.Active);
List<PortalView.LookupListItemBO> oList = LookupListBA.LookupListItem_GetList_ByLookupListId(DB_Context, list.LookupListId, (Guid)Current.Employee.SiteId);
var AssetList = oList.Select(l => new { AssetTypeName = l.Name });
rddl.ID = "ddlAssetTypeName";
rddl.AutoPostBack = false;
rddl.DataSource = AssetList;
rddl.DataTextField = "AssetTypeName";
rddl.DataValueField = "AssetTypeName";
rddl.DataBind();
edit["AssetTypeName"].Controls.Add(rddl);
}
}
I tried retrieving the selected value in the UpdateCommand, but have been unsuccessful:
protected void grdAssetImport_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
{
GridEditableItem editableItem = e.Item as GridEditableItem;
DropDownList ddl = editableItem.FindControl("ddlAssetTypeName") as DropDownList;
if(ddl != null)
{
string assetType = ddl.SelectedValue;
}
DropDownList ddl2 = editableItem["AssetTypeName"].Controls[0] as DropDownList;
if(ddl2 != null)
{
string assetType = ddl.SelectedValue;
}
if (column is IGridEditableColumn)
{
IGridEditableColumn editableCol = (column as IGridEditableColumn);
if (editableCol.IsEditable)
{
IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
string editorText = "unknown";
object editorValue = null;
if (editor is GridTextColumnEditor)
{
editorText = (editor as GridTextColumnEditor).Text;
editorValue = (editor as GridTextColumnEditor).Text;
}
if (editor is GridBoolColumnEditor)
{
editorText = (editor as GridBoolColumnEditor).Value.ToString();
editorValue = (editor as GridBoolColumnEditor).Value;
}
if (editor is GridDropDownColumnEditor)
{
editorText = (editor as GridDropDownColumnEditor).SelectedText + "; " +
(editor as GridDropDownColumnEditor).SelectedValue;
editorValue = (editor as GridDropDownColumnEditor).SelectedValue;
}
try
{
DataRow[] changedRows = this.AssetGridDataSource.Select("Id = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Id"].ToString());
changedRows[0][column.UniqueName] = editorValue;
this.AssetGridDataSource.AcceptChanges();
GetSearchColumns();
}
catch (Exception ex)
{
// Label1.Text = "<strong>Unable to set value of column '" + column.UniqueName + "'</strong> - " + ex.Message;
e.Canceled = true;
break;
}
}
}
}
}
It never finds the dropdownlist, and always only sees the GridTextColumnEditor of the column so the only value I get is the original value before edit mode.
Any assistance is greatly appreciated!
Items do not bind every time and so the ItemDataBound event fires less times than you think. To add a control every time an item is created, you would need to use the ItemCreated event instead.
I've tested the following and works.
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem edititem = e.Item as GridEditableItem;
DropDownList rddl = new DropDownList();
edititem["AssetTypeName"].Controls[0].Visible = false;
rddl.ID = "ddlAssetTypeName";
rddl.AutoPostBack = false;
rddl.DataSource = Enumerable.Range(1, 3).Select(x => "Item" + x).ToList();
rddl.DataBind();
edititem["AssetTypeName"].Controls.Add(rddl);
}
}
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
DropDownList ddl = editedItem["AssetTypeName"].FindControl("ddlAssetTypeName") as DropDownList;
string selectedValue = ddl.SelectedValue;
}

In WPF is it possible to force an update to a datagrid on keyup event?

I have a datagrid with multiple rows and columns. One of the columns is a numeric value. The user can edit this column to change the value in this cell/column. This column is totaled and the number is displayed under the datagrid. I want to have this number update as soon as the user enter a number. On the KeyUp event I call a routine that unloads the datagrid to a datatable and then I read through the column and count the value in this column. However when the datagrid is unloaded the original value is still the cell value. Is there away to force the update before I unload the datagsrid?
Here is my code:
private void dtGrid_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int intKeyValue;
try
{
if (dtGrid.CurrentColumn.DisplayIndex == 1)
{
if (e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Tab || e.Key == Key.NumLock)
{
SendKeys.SendWait("{TAB}");
}
else
{
intKeyValue = GetNumericValue(e.Key.ToString());
if (e.Key == Key.LeftShift || e.Key == Key.RightShift || e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
{
e.Handled = true;
}
else
{
if (intKeyValue < 0 || intKeyValue > 9)
{
System.Windows.MessageBox.Show("Only numbers are allowed.");
e.Handled = true;
}
}
}
}
}
catch (Exception ex)
{
string strMsg = "Error occured in Start Row key event. ";
System.Windows.MessageBox.Show(strMsg + ex.Message);
//throw new NotImplementedException();
}
}
private void dtGrid_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
UpdateRowSize();
}
private void UpdateRowSize()
{
DataTable dtFieldSizes = new DataTable();
int intRowSize;
string strTotalRowSizeData;
string[] strRowSizeInfo;
try
{
intRowSize = 0;
dtGrid.UpdateLayout();
dtFieldSizes = ((DataView)dtGrid.ItemsSource).ToTable();
for (int intRowCnt = 0; intRowCnt < dtFieldSizes.Rows.Count; intRowCnt++)
{
intRowSize += Convert.ToInt16(dtFieldSizes.Rows[intRowCnt]["Size"]);
}
strTotalRowSizeData = lblRowSize.Content.ToString();
strRowSizeInfo = strTotalRowSizeData.Split(':');
if (Convert.ToInt16(strRowSizeInfo[1]) != intRowSize)
{
lblRowSize.Content = strRowSizeInfo[0] + ": " + Convert.ToString(intRowSize);
}
}
catch (Exception ex)
{
string strMsg;
strMsg = "RefreshRowSize, error '" + ex.Message + "' has occurred.";
System.Windows.MessageBox.Show(strMsg);
}
}
You can handle AutoGeneratingColumn and set UpdateSourceTrigger of the column Binding to be PropertyChanged. Assuming that this is your DataTable:
var tab = new DataTable();
tab.Columns.Add("a", typeof(double));
tab.Rows.Add(tab.NewRow());
tab.Rows[0][0] = 45;
And this is your DataGrid and its ItemsSource:
DataGrid gr = new DataGrid();
gr.ItemsSource = tab.AsDataView();
Handle:
gr.AutoGeneratingColumn += Gr_AutoGeneratingColumn;
in which
private void Gr_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridTextColumn col = e.Column as DataGridTextColumn;
if (col != null)
{
Binding binding = new Binding("[" + col.Header.ToString() + "]");
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
col.Binding = binding;
}
}
In this setting, the value of the DataGrid updates, while you are typing in the cell.
Instead of updating the value datagrid keydown/up event, you can try with DataGridCell' keyup/keydown event

C# Sorting lost when going to new page

I have an issue with my sorting when navigating between pages. When I go to a new page, the sorting order is lost and the user has to sort again.
I have ran through my code and know the issue lies in PageIndexChanging event of the gridview. Where am rebind the gridview with fresh data.
However, I am not sure how to avoid this? How do I store the sort order when rebinding the gridview? ViewState perhaps?
Any suggestions please?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateProductClass();
PopulateProduct();
PopulateOrderList();
}
}
private void PopulateOrderList()
{
DateTime d;
DateTime d2;
CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
int nKustomerID = ki.CustomerID;
DataTable dts = new DataTable();
dts.Columns.Add("OrderDate", typeof(DateTime));
dts.Columns.Add("OrderNumber", typeof(string));
dts.Columns.Add("OrderItemSKUName", typeof(string));
dts.Columns.Add("SKUNumber", typeof(string));
dts.Columns.Add("OrderItemStatus", typeof(string));
dts.Columns.Add("OrderItemUnitCount", typeof(string));
dts.Columns.Add("mtrx_Code2", typeof(string));
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#CustomerID", nKustomerID);
if (drpProductClass.SelectedValue.ToString() != "0" || drpProductClass.SelectedValue.ToString() == null) { qdp.Add("#OrderItemWRClass", drpProductClass.SelectedItem.ToString()); }
if (drpProduct.SelectedValue.ToString() != "0") { qdp.Add("#OrderItemSKUID", drpProduct.SelectedValue.ToString()); }
if (txtStartDate.Text != "") { d = DateTime.Parse(txtStartDate.Text); qdp.Add("#OrderItemDateFrom", d.ToString("yyyy-MM-dd")); }
if (txtEndDate.Text != "") { d2 = DateTime.Parse(txtEndDate.Text); qdp.Add("#OrderItemDateTo", d2.ToString("yyyy-MM-dd")); }
DataSet ds = gc.ExecuteQuery("CN_GetOrderItemByCustID", qdp, QueryTypeEnum.StoredProcedure, true);
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow drNew = dts.NewRow();
drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
drNew["OrderNumber"] = dr["OrderNumber"].ToString();
drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
drNew["SKUNumber"] = dr["SKUNumber"].ToString();
drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
drNew["mtrx_Code2"] = dr["mtrx_Code2"].ToString();
dts.Rows.Add(drNew);
}
//Clear the TextBox
litResults.Text = String.Empty;
if (dts.Rows.Count == 1)
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
else
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
try
{
Session["Data"] = dts;
}
catch(Exception ex)
{
throw ex;
}
gvOrderItems.Visible = true;
gvOrderItems.DataSource = dts.DefaultView;
gvOrderItems.DataBind();
if (dts.Rows.Count > 1) litResults.Text += " - Showing page " + (gvOrderItems.PageIndex + 1).ToString() + " of " + gvOrderItems.PageCount.ToString();
}
private string SortCriteria
{
get
{
if (ViewState["sortCriteria"] == null)
{
ViewState["sortCriteria"] = "";
}
return ViewState["sortCriteria"].ToString();
}
set
{
ViewState["sortCriteria"] = value;
}
}
public SortDirection SortDirection
{
get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set
{
ViewState["SortDirection"] = value;
}
}
protected void gvOrderItems_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string direction = string.Empty;
DataTable dt = (DataTable)Session["Data"];
if (dt.Rows.Count > 0)
{
DataView dataView = new DataView(dt);
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
dataView.Sort = sortExpression + direction;
gvOrderItems.DataSource = dataView;
gvOrderItems.DataBind();
}
}
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
PopulateOrderList();
}
Maybe you're databinding the GridView on every postback from Page_Load.
You should do that only at the first time. Use the Page.IsPostBack property:
protected void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
// GridBind here
}
Resolved my issue thanks to Vignesh on suggesting of using ViewState. However I choose to use a Session variable.
Inside the sorting event handler, after the sorting is carried out I stored the sorted list in a Session Session["SortedView"] = dataView;. Now during the PageIndexChanging1 I check if this session variable is empty and use accordingly.
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
if (Session["SortedView"] != null)
{
gvOrderItems.DataSource = Session["SortedView"];
gvOrderItems.DataBind();
}
else
{
PopulateOrderList();
}
}

Can't find selected item in listbox C# ASP.NET

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//int test = Convert.ToInt32(ListBox1.SelectedValue.ToString());
//GetById(test);
foreach (ListItem listitem in ListBox1.Items)
{
if (listitem.Selected == true)
{
string email = listitem.Text;
GetByEmail(email);
}
}
}
This method should get selected item.I don't why but it show me that property selected is false for all items.
protected void Page_Load(object sender, EventArgs e)
{
ListBox1.Items.Clear();
SelectAllUsers();
}
public void SelectAllUsers()
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolService.User[] userArray = client.SelectAll(0);
int i = 0;
while (i < userArray.Length)
{
ListItem listItem = new ListItem();
listItem.Text = userArray[i].Email;
listItem.Value = userArray[i].Id.ToString();
ListBox1.Items.Add(listItem);
i++;
}
}
public void GetByEmail(string email)
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolClient.SchoolService.User user = client.GetUserByEmail(email);
if ((user.FirstName != null) || (user.LastName != null) || (user.Address != null) ||
(user.City != null) || (user.Email != null) || (user.Password != null))
{
txtId.Text = user.Id.ToString();
txtFirstName.Text = user.FirstName.ToString();
txtLastName.Text = user.LastName.ToString();
txtAddress.Text = user.Address.ToString();
txtCity.Text = user.City.ToString();
txtDateOfBirth.Text = user.DateOfBirth.ToShortDateString();
txtEmail.Text = user.Email.ToString();
txtPassword.Text = user.Password.ToString();
txtIsAdmin.Text = user.isAdmin.ToString();
}
else
{
MsgBox("None user was found", this.Page, this);
}
}
public void SelectAllUsers()
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolService.User[] userArray = client.SelectAll(0);
int i = 0;
while (i < userArray.Length)
{
//if (userArray[i] != null)
//{
ListItem listItem = new ListItem();
listItem.Text = userArray[i].Email;
listItem.Value = userArray[i].Id.ToString();
ListBox1.Items.Add(listItem);
//}
i++;
}
}
Also sent methods which fill listBox with items (SelectAllUsers), and method which should take selected item from database (GetByEmail)
It doesn't find anything selected because on Page_Load you are rebinding the data again every time. You need to check if IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListBox1.Items.Clear();
SelectAllUsers();
}
}

cannot see the label content when a item is selected from dynamically added dropdownlist

I have a Dropdownlist (DDL1) when I select any item from this dropdownlist(DDL1), results in creation of another dropdownlist(DDL2), This contains some of the items.When I select other Item from DDL1 , Items will change in DDL2, this happens for the each different item selected in DDL1.
when I select a item from DDL2, label content must be shown, intially I'm making Label invisibe and in the code I changed the visibility to true and added content to it. But the label content is not shown when I select a item from DDL2.
Here is my Code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Remove("Chacha Choudary");
DropDownSeller.Items.Remove("SpiderMan");
DropDownSeller.Items.Remove("Amar chitra Katha");
DropDownSeller.Items.Remove("Chandamama");
DropDownSeller.Items.Remove("Mahabharata");
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}
Any ideas on this are appreciated
Thanks,
Remove if (!Page.IsPostBack) from the DropDownList1_SelectedIndexChanged because when the page postbacks this condition will be false. Because your page is posting back to the server that's why it is not visible and not showing.
In short your DropDownList1_SelectedIndexChanged should be like..
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Clear(); // it will clear all the items, instead you are removing one by one
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
}
protected void DropDownSeller_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}

Categories

Resources