I have a function:
private void ds_ItemBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemIndex >= 0)
{
e.Item.Cells[0].Controls.Add(Utility.GetImage("Delegate"));
e.Item.Attributes.Add("Description", ((System.Data.DataRowView)(e.Item.DataItem)).Row["DelegateDescription"].ToString());
string DelegateName = ((System.Data.DataRowView)(e.Item.DataItem)).Row["DelegateName"].ToString();
e.Item.Attributes.Add("DelegateName", ((System.Data.DataRowView)(e.Item.DataItem)).Row["DelegateName"].ToString());
((System.Web.UI.WebControls.CheckBox)(e.Item.Cells[3].Controls[0])).Checked = false;
if (hDelegates.Value != "")
{
string[] selectedDelegates = hDelegates.Value.Split(new char[] { ',' });
foreach (string delegate in selectedDelegates)
{
if (delegate.Equals(delegateName))
{
count++;
((System.Web.UI.WebControls.CheckBox)(e.Item.Cells[3].Controls[0])).Checked = true;
break;
}
}
}
}
if (count == dDelegates.Items.Count)
lblEditCheck.Checked = true;
else
lblEditCheck.Checked = false;
}
The UI has a table with each row corresponding to one entry. So, each row has an image, a description, a name.
I am getting an exception in the code at line:
((System.Web.UI.WebControls.CheckBox)(e.Item.Cells[3].Controls[0])).Checked = false;
The exception is : Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.CheckBox'.
Further, e.Item.Cells[3].Controls[0] is System.Web.UI.LiteralControl .
And the the check box markup looks like <asp:CheckBox ID="lblEditCheck" runat="server" TabIndex="0" Width="30px" CssClass="ColumnHeader" /></td>
I am stuck on getting this to work for a few days now. Please let me know if any more info will be useful.
Thanks a lot for your help.
What didn't work:
var checkbox = (System.Web.UI.WebControls.CheckBox)e.Item.FindControl("lblEditCheck");
checkbox.Checked = false;
In this case checkbox is null. And the corresponding exception is thrown.
Use IDs of the controls which you want to get and use the FindControl to get the CheckBox. Also use the ListViewItemType.DataItem for data rows as you will get the null for non DataItem rows.
if (e.Item.ItemType == ListViewItemType.DataItem)
{
((System.Web.UI.WebControls.CheckBox)(e.Item.FindControl("lblEditCheck")).Checked = false;
}
If you expect the some of row may not have the checkbox control then you can first get the checkbox and then change it Changed status.
CheckBox lblEditCheck = e.Item.FindControl("lblEditCheck") as CheckBox;
if(lblEditCheck != null)
lblEditCheck.Checked = false;
Related
I need to to use a checkboxlist because there is a unique case the user is allowed to select 3 items at the same time. Problem is that I can't even manage to get the single selection to work. I'm doing this is codebehind with an updatepanel to not refresh the page.
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
int count = 0;
int i = 0;
int maxObjects = cblCodeRequest.Items.Count;
string[] checkObjects = new string[maxObjects];
ListItem selectedItem = new ListItem();
foreach (ListItem item in cblCodeRequest.Items)
{
checkObjects[i] = item.Text;
i++;
}
foreach (ListItem item in cblCodeRequest.Items)
{
if (item.Selected)
{
count++;
selectedItem = item;
cblCodeRequest.ClearSelection();
}
foreach (ListItem itm in cblCodeRequest.Items)
{
if (item.Equals(selectedItem))
{
item.Selected = true;
}
}
}
}
I'm not sure how to proceed from here, i already save the selected item and clear the whole selection and then set it again but it doesn't do it, it just selects itself again after even if i click a different checkbox. I think my logic is messed up
Try this, Your foreach statements are not arranged correctly
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedItem = cblCodeRequest.Items[cblCodeRequest.SelectedIndex]
cblCodeRequest.ClearSelection();
int x = 0;
for(x; x<cblCodeRequest.Items.Count; x++)
{
if (cblCodeRequest.Items[x].Equals(selectedItem))
{
item.Selected = true;
}
}
}
Ok, I finally solved this problem. I had to dig through the problem with the debugger and follow the logic. I did this in jQuery so I can remove the update panel. If Anyone ever gets the same problem as me, this is the solution for you.
This allows you to use a checkboxlist like a radiobuttonlist but also allows you to check multiple checkboxes that belong to a special selection group.
$(function () {
$('[id*=cblCodeRequest] input').on('click', function () {
var checkboxlist = $('[id*=cblCodeRequest]'); // CheckBoxList
var checkboxArray = $('[id*=cblCodeRequest] input'); // CheckBoxList Items
var current = $(this); // Get Selected Checkbox
var label = $(current).next().text(); // Get CheckBox label name
// Uncheck every checkBox that don't match the unique multi selection combo
if (label != "Recâmbio" && label != "Série" && label != "Embalagem Alternativa") {
// Loop through checkboxArray and uncheck every item that does not meet the condition
$(checkboxArray).each(function (i) {
$(this).prop("checked", false);
});
// Check the selected item again
$(current).prop("checked", true);
} else {
// Get the current checkbox name
var chk = $(current).next().text();
// If the checkbox that matches the unique combo selection was click uncheck all invalid checkboxes that don't match
if (chk == "Série" || chk == "Recâmbio" || chk == "Embalagem Alternativa") {
// loop through the checkboxlist again
$(checkboxArray).each(function () {
// Get the looped item name
var ck = $(this).next().text();
// if checkbox does not belong to the unique combo selection, uncheck it
if (ck != "Recâmbio" && ck != "Série" && ck != "Embalagem Alternativa") {
$(this).prop("checked", false);
}
});
}
}
});
});
I have a drop down list "ddlMitchelLandscape2" ,when add button triggers ,i add the selected item value in to gridview.
I am stuck here ,how to check the gridview, before add the value to grid view. The selected item is already exist in grid view or not when the add button is triggered .
Some one help me how to check the value is exist in gridview before add it to gird view please ?
protected void btnAddMitchellLandscape_Click(object sender, EventArgs e)
{
//validate to make sure Mitchell Landscape is entered
if (!ValidateMitchellPage())
return;
Assessment objAssessment = (Assessment)Session[Session_CurrentAssessment];
if (ddlMitchelLandscape2.GetSelectedItemValue > 0)
{
if (lblMitchellID.Text == string.Empty)
{
//add
AssessmentEntity objAssessmentEntity = new AssessmentEntity();
Assessment.tblMitchellLandscapeIDRow row =
objAssessment.tblMitchellLandscapeID.NewtblMitchellLandscapeIDRow();
row.MitchellLandscapeID = ddlMitchelLandscape2.GetSelectedItemValue;
row.MitchellLandscapeName = ddlMitchelLandscape2.GetSelectedItemText;
}
else
{
//Add button not visible when its not a new row
ctrlHeader.ShowError("Error: Unknown error");
return;
}
//refresh data bound table
PopulateMitchellDetailsToForm(ref objAssessment);
//clear after save
btnClearMitchellLandscape_Click(null, null);
}
}
ValidateMitchellPage()
private bool ValidateMitchellPage()
{
litMitchellError.Text = string.Empty;
if (ddlMitchelLandscape2.GetSelectedItemValue <= 0)
litMitchellError.Text = "Please select Mitchell Landscape";
if (litMitchellError.Text.Trim() == string.Empty)
{
litMitchellError.Visible = false;
return true;
}
litMitchellError.Visible = true;
return false;
}
DataBind to grid view
private void PopulateMitchellDetailsToForm(ref Assessment objAssessment)
{
Assessment.tblMitchellLandscapeIDRow[] MlData
= (Assessment.tblMitchellLandscapeIDRow[])objAssessment.tblMitchellLandscapeID.Select("SaveType <> " + Convert.ToString((int)EnumCollection.SaveType.RemoveOnly));
this.gvMitchellLandscape.DataSource = MlData;
this.gvMitchellLandscape.DataBind();
}
You have to check the selected value from the dropdown or combobox in gridview by checking each row.
You can use following code to get row of gridview.
bool isValueExist=False;
for (int i = 0; i < gridview.Rows.Count; i++)
{
String val = gridview.Rows[i].Cells[0].Value.ToString();
if(val == your_drop_down_value)
{
isValueExist=True;
break;
}
}
You have to change the cell number according to your gridview design.
I can edit single row in the GridView.
But when in MySQL database the value of field "card" is not null I need stopping the edit in this single row of GridView (and passed the row in closed state).
I tried this solution, but in GridView I've all rows of GridView in "closed state" even when the value of field "card" is null, why?
The condition is inserted in RowDataBound event, it's correct?
My code below.
I would greatly appreciate any help you can give me in working this problem.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var obj = ((DataRowView)e.Row.DataItem)["card"];
ImageButton edit = (ImageButton)e.Row.FindControl("imgbtnEdit");
if (obj != null)
{
edit.Enabled = false;
edit.ToolTip = "Closed state";
}
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
This is because DBNull.Value and null are two different things.
var obj = ((DataRowView)e.Row.DataItem)["card"];
if (!DBNull.Value.Equals(obj))
{
edit.Enabled = false;
edit.ToolTip = "Closed state";
}
This will check to see if the "card" value is a null database value, rather than a null object.
Using MS Visual Studio 2012, Telerik, C#.ASP.NET.
The logic I need is as follows:
If a columns data on all rows is null then hide the column
Basically if a column has 3 rows of data, if there all null then dont bother displaying that column, however if there is a value in 1 of them, then show the column.
been playing around:
foreach (GridColumn columns in dgvUserResults.Columns)
{
if (columns != null)
{
columns.Visible = false;
}
else
{
columns.Visible = true;
}
}
code doesn't work of course doesnt iterate through the foreach loop just skips it. Although not bothered about that even if it did iterate through I need a way to check if all column[name] rows are null. There a nice Telerik one liner?
Please try with below code snippet.
Using UniqueName
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
{
// If you used ClientSelectColumn then below code is not worked For that you have to put condition
//if(column.ColumnType == "GridBoundColumn")
int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
item[column.UniqueName].Text == " "
select item).ToList().Count;
if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
{
RadGrid1.MasterTableView.Columns.FindByUniqueName(column.UniqueName).Visible = false;
}
}
}
By Using Index
protected void RadGrid1_PreRender(object sender, EventArgs e)
{
foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
{
// If you used ClientSelectColumn then below code is not worked For that you have to put condition
//if(column.ColumnType == "GridBoundColumn")
int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
item[column.UniqueName].Text == " "
select item).ToList().Count;
if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
{
column.Visible = false;
}
}
}
For col = 0 To myRadGridView.ColumnCount
Dim mustKeepColumn As Boolean = False
For Each r In myRadGridView.Rows
If Not String.IsNullOrEmpty(r.Cells(col).Value.ToString) Then
mustKeepColumn = True
Exit For
End If
Next
If Not mustKeepColumn Then
myRadGridView.Columns(col).IsVisible = False
End If
Next
So I am recieving some postback data back from a form and need to get the checkbox values for a group of checkboxes in a parent control. I coded it up and it was working but now no longer works and I can not figure out why. The checkboxes are created on page load dynamically but on postback nothing seems to be checked when the form had checked items, the only postback event is the submit button event.
// This is from the btnSubmit Postback event that isn't working anymore
foreach (CheckBox cb in ShowPermissions.Controls.OfType<CheckBox>())
{
if (cb.Checked)
{
// Add New Admins Permissions
Permission p = new Permission();
p.AdminUserID = au.id;
p.AdminMenuID = Convert.ToInt32(cb.ID.ToString().Substring(4));
ngdb.Permissions.InsertOnSubmit(p);
submitResult.InnerHtml += cb.ID.ToString();
// Does not run now?
}
// can see the checkbox object
}
protected void Page_Load(object sender, EventArgs e)
{
FunctionType = Request.QueryString["func"] != null && Request.QueryString["func"] != "" ? Request.QueryString["func"] : null;
RID = Request.QueryString["rid"] != null && Request.QueryString["rid"] != "" ? int.Parse(Request.QueryString["rid"]) : -1;
PopulateAdminTypes();
if (!IsPostBack && FunctionType == "edit" && RID != -1)
{
// Populate User details for Edit
PopulateUser(RID);
// Populate checkboxes and check selected options
PopulateAdminPermissionOptions(true, RID);
// Disable password change
ChangePassword(false);
}
else if (!IsPostBack)
{
chkChangePassword.Visible = false;
PopulateAdminPermissionOptions(false, -1);
}
}
private void PopulateAdminPermissionOptions(bool blnPopulateForEdit, int RID)
{
// Get Logged in Admin ID
int intAdminId = Convert.ToInt32(Session["AdminID"]);
int intAdminTypeId = Convert.ToInt32(Session["AdminTypeID"]);
using (NewGeorgeDataContext ngdb = new NewGeorgeDataContext())
{
var am = ngdb.AdminMenus.AsQueryable();
// Hide Add and Edit Options from Non Super Users
var amUsers = ngdb.AdminMenus.Where(x => x.id > 2 && x.id < 5);
if (intAdminTypeId > 1) am = am.Except(amUsers);
foreach (var m in am.OrderBy(x => x.MenuTypeID).ThenBy(x => x.id))
{
// Add New CheckBox
CheckBox cb = new CheckBox();
cb.ID = "chk_" + m.id;
cb.CssClass = "chkItems";
cb.Text = m.AdminMenuType.Name + ": " + m.Name;
// Get Admin Permission objects
if (blnPopulateForEdit)
{
var ap = ngdb.Permissions.SingleOrDefault(x => x.AdminUserID == RID && x.AdminMenuID == m.id);
if (ap != null)
{
cb.Checked = true;
}
}
ShowPermissions.Controls.Add(new LiteralControl("<p>"));
ShowPermissions.Controls.Add(cb);
ShowPermissions.Controls.Add(new LiteralControl("</p>"));
}
}
}
Can someone workout what I cannot see atm?
The view state isn't getting load into your controls. You must create all the controls before LoadViewState triggers. So, create all dynamic Controls OnPageInit event or Page_Init method to get the correct behavior. Take a look here to get more information about Asp.NET Page Life Cycle
Hopes this help you!