programmatically check checkbox asp.net - c#

Im trying to loop through a collection and create checkboxes for each item in the collection. I check if a bool is true and want that checkbox to be checked. But I cant seem to get this to work. What am I missing here?
var checkboxList = new CheckBoxList();
foreach (var answer in question.Answers)
{
if (answer.CorrectAnswer)
{
var cbItemOrd = new CheckBox
{
Checked = true,
Text = answer.AnswerText + " Correct Answer"
};
checkboxList.Items.Add( cbItemOrd.Text );
cbItemOrd.Checked = true;
}
else
{
checkboxList.Items.Add(answer.AnswerText);
}
}
div.Controls.Add(checkboxList);
I get the "correct answer" text out on the correct field so the loop works. If I need to use "FindControl" or something, how do I do that with programmatically created objects?
Thanks alot!

Related

Clicking on List Item on Dropdown

I'm having a problem in interacting with a custom dropdown control. It works fine the 1st 6 times, but after that, since the screen is resized, it could no longer locate and click the option in the dropdown control, returning an exception - can't click on hidden control. I tried putting in a itemField.DrawHighlight(); on the control I'm looking for, and it finds it, however it can't click on it. I also tried a to scroll down, but it seems to be not working.
bool addItemCheck = false;
int scrollCheck = 0;
while (Check == false)
{
var addItem= new HtmlButton(window);
addItem.SearchProperties.Add(HtmlButton.PropertyNames.Id, "add-new-item");
Mouse.Click(addItem);
scrollCheck = scrollCheck + 1;
if (scrollCheck > 6)
{
Mouse.MoveScrollWheel(window, -100);
}
var itemDropDown = new HtmlSpan(window);
itemDropDown .SearchProperties.Add(HtmlSpan.PropertyNames.Class, "item-dropdown");
itemDropDown .SearchProperties.Add(HtmlSpan.PropertyNames.InnerText, "Select an Item");
Mouse.Click(itemDropDown );
addItemCheck = itemDropDown.Exists;
}
bool itemBoxCheck = false;
HtmlCustom itemBox = null;
while (itemBoxCheck == false)
{
itemBox = new HtmlCustom(window);
itemBox.SearchProperties.Add(HtmlCustom.PropertyNames.Id, "item-listbox");
var itemField = new HtmlCustom(itemBox);
itemField .SearchProperties.Add(HtmlCustom.PropertyNames.InnerText, item);
Mouse.Click(itemField);
itemBoxCheck = itemBox.Exists;
}
I would really appreciate any help. Thank you.
Try calling the method InsureClickable() on the control before attempting to click on it.
for example:
itemDropDown.EnsureClickable();
Mouse.Click(itemDropDown);
Edit:
if this doesn't work you'll have to scroll down to the item.
try using:
Mouse.MoveScrollWheel()
if that doesn't work also you'll have to map the scroll control and click on it.

Simple ListBoxItem Issue, not sure how to write this into the code correctly

lblSelected.Text = string.Empty; // empty the label that says you already have an item
foreach (GridViewRow row in gvSnacktastic.Rows) // check all the items in the grid view
{
CheckBox checkItOut = row.Cells[0].Controls[0] as CheckBox; // get the checkbox
if (checkItOut != null && checkItOut.Checked) // if the checkbox exists and is checked
{
bool storeVariable = true; // store a variable that tells us if we need to add it to the list
**foreach(ListBoxItem listItem in lbSelected.Items)** // Loop through list box items to see if we already have it. i haven't used listbox in a long time, this might be slightly wrong
{
// I'm not sure if it's .Text - compare the text of the listbox item to the checkbox item description
if(listItem.Text== checkItOut.Text)
{
lblSelected.Text = "The Item " + listItem.Text + " has already been added."; // make our already have it label
storeVariable = false; // remember that we don't need to add this item
}
}
if(storeVariable) // if we do need to add this item
{
lbSelected.Items.Add(checkItOut.Text); // create a new list box item with the check box item's description - this code is not complete
}
}
}
}
The highlighted (**) area is reading with an error as I am debugging. Any idea what I'm doing wrong?
I'm sure this is a simple question to answer, but I am not finding the right information online.
Please Change
foreach(ListBoxItem listItem in lbSelected.Items)
{
}
TO
foreach(ListItem listItem in lbSelected.Items)
{
}

Text.Replace in gridview replacing entire cell

I have a gridview that is bound to a sql database. As the user enters data they must indicate whether that cell's information is complete or not. To do this they enter /end/ at the end of their statement and it will automatically change the cell color. If nothing is entered then nothing happens.
Here is the code:
if (dataItem != null)
{
var label = dataItem["Status"].FindControl("Statuslbl") as Label;
if (label != null)
{
var item = dataItem;
var text = label.Text;
if (text.Contains("/end/"))
{
item["Status"].BackColor = Color.Lime;
item["Status"].Text = item["Status"].Text.Replace(#"/end/", #"");
}
else
{
item["Status"].BackColor = Color.Salmon;
}
}
}
Instead of just hiding the '/end/' like I need it to, it hides the entire cells contents.
How can I go about fixing this?
Discovered all I would need to do would be the following to achieve my result:
if (text.Contains("/end/"))
{
item["Test"].BackColor = Color.Lime;
item["Test"].Text = label.Text.Replace("/end/", " ");
}
Really simple, I just needed to use label.Text.

Hide some datagridview checkbox cell

I have a datagridview showing installments of a loan. I created a datagridviewcheckbox column so then I can select all the installments i want to pay for.
This is a screen of the datagrid:
My issue is that I need to disable the checkboxes of the paid intallments. In this case, when "Restante" (what´s left to pay) is = 0.
I read some posts where they used the paint event to not show the checkbox cell, but i didnt like that solution. I thought of hiding the checkbox cell, but i don´t know if it is possible to do that.
Thats what i tried:
foreach (DataGridViewRow row in dgv_Cuotas.Rows)
{
if (Convert.ToDecimal(dgv_Cuotas.Rows[row.Index].Cells[17].Value) == 0)
{
dgv_Cuotas.Rows[row.Index].Cells[16].Visible = false;
}
}
Obviously this does not works, I get a compiler error message saying that the property is read only.
Does somebody knows how to set the checkbox cell to invisible?
Just in case, I attach the DataGridViewCheckboxColumn creation code:
DataGridViewCheckBoxColumn chbox = new DataGridViewCheckBoxColumn();
{
chbox.CellTemplate = new DataGridViewCheckBoxCell();
chbox.HeaderText = "";
chbox.Name = "Seleccionar";
chbox.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
chbox.FlatStyle = FlatStyle.Standard;
}
dgv_Cuotas.Columns.Insert(16, chbox);
dgv_Cuotas.Columns[16].DisplayIndex = 0;
EDIT:
Some considerations:
I use the cell content click event to handle the checkboxes, so readonly wont work. What I want is to hide the checkbox:
private void dgv_Cuotas_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
if (dgv_Cuotas.Columns[e.ColumnIndex].Name == "Seleccionar")
{
DataGridViewRow row = dgv_Cuotas.Rows[e.RowIndex];
DataGridViewCheckBoxCell cellSeleccion = row.Cells["Seleccionar"] as DataGridViewCheckBoxCell;
int n_cuota = Convert.ToInt32(dgv_Cuotas[2, dgv_Cuotas.CurrentRow.Index].Value);
Cuota cuota_seleccionada = new Cuota();
cuota_seleccionada = Lista_cuotas.Where(x => x.num_cuota == n_cuota).First();
if (cellSeleccion != null && Convert.ToBoolean(cellSeleccion.Value) == true)
{
cellSeleccion.Value = false;
Actualizar_cuotas_seleccionadas(false, cuota_seleccionada);
}
else
{
if (cellSeleccion != null && Convert.ToBoolean(cellSeleccion.Value) == false)
{
cellSeleccion.Value = true;
Actualizar_cuotas_seleccionadas(true, cuota_seleccionada);
}
}
}
In the other hand, I´m already using the Onpaint event. Its inherited, thats why I´m trying to avoid using it.
Assign a value to the checkbox cell. Then Convert it to a TextBox with a new value.
Worked for me.
dataGridView1.Rows[row.Index].Cells[16].Value = false;
dataGridView1.Rows[row.Index].Cells[16] = new DataGridViewTextBoxCell();
dataGridView1.Rows[row.Index].Cells[16].Value = "";
Yes, you can do this by Converting the DataGridViewCheckBoxCell to DataGridViewTextBoxCell
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (dataGridView1.Rows[row.Index].Cells[17].EditedFormattedValue.ToString().Length == 0) // if (string.IsNullOrWhiteSpace(dataGridView1.Rows[row.Index].Cells[4].EditedFormattedValue.ToString()))
break;
if (Convert.ToDecimal(dataGridView1.Rows[row.Index].Cells[17].EditedFormattedValue) == 0)
{
dataGridView1.Rows[row.Index].Cells[16].Value = null;
dataGridView1.Rows[row.Index].Cells[16] = new DataGridViewTextBoxCell();
}
else
{
//dgv_Cuotas.Rows[row.Index].Cells[16] = new DataGridViewCheckBoxCell();
}
}
Use the cell's ReadOnly attribute to disable any modification.
If you want to turn it to hidden, you need to override the painting code for the cells.
Try to hide it and the value remains, which should prevent runtime errors.
dataGridView1.Rows[row.Index].Cells[16].Style.Padding =
new Padding(dataGridView1.Rows[row.Index].Cells[16].OwningColumn.Width, 0, 0, 0);
I took spajce's answer and tweaked it a bit to make it work for me.
for (var i = 0; i < datagridview1.Count; i++)
{
if ((bool)datagridview1[0, i])
{
datagridview1[0, i] = new DataGridViewTextBoxCell
{
Style = { ForeColor = Color.Transparent,
SelectionForeColor = Color.Transparent }
};
}
}
We're basically iterating through the rows and looking for a 'true' checked box. If it's checked then we're converting the box to a text box and setting its text color to Transparent so the cell looks empty. I hope this helps everyone who had this problem, I spent hours trying to find a workable answer.
There are several ways to accomplish what you want.
For example, you can use the Readonly property of the cell to avoid the user to change the values and change the appeareance of the control to look grayed:
C# DataGridViewCheckBoxColumn Hide/Gray-Out
A simple and effective alternative is to use the chkbox ThreeState property. In code below, if my object does not have an email address, then I don't want to allow the user to tick the checkbox for sending email. To do this, the check box value is set to Unknown and read-only, which means it is displayed as "unselectable" and user cannot modify.
chk = DirectCast(row.Cells(m_idxEmailChecked), DataGridViewCheckBoxCell)
If String.IsNullOrEmpty(contact.EmailAddress) Then
chk.Value = enumTristate.Unknown
chk.ReadOnly = True
Else
chk.ThreeState = False
End If
Note this also requires several associated ThreeState properties to be set on the checkbox.
.ValueType = GetType(enumTristate)
.TrueValue = enumTristate.True
.FalseValue = enumTristate.False
.IndeterminateValue = enumTristate.Unknown
.ThreeState = True
Good luck.
I tried Charlie's way:
dataGridView1.Rows[row.Index].Cells[16].Value = false;
dataGridView1.Rows[row.Index].Cells[16] = new DataGridViewTextBoxCell();
dataGridView1.Rows[row.Index].Cells[16].Value = "";
I got fewer errors, but still kept getting them. So I tried to instantiate the new DataGridViewTextBoxCell separately, and that did the trick for me (I didn't need to set the checkbox cell value either):
DataGridViewTextBoxCell c = new DataGridViewTextBoxCell();
c.Value = "";
dataGridView1.Rows[row.Index].Cells[16] = c;
Hope that helps someone!

Clone a DataBound Checked List Box

I have a DataBound CheckedListBox, I "check" few items on list box(source), then I need to clone it to new Checked List Box(target). It need to have all the data, with checked state. I have tried with following function. It is properly flowing through this function.
But finally I can see items on target CheckedListBox but none of the items in target is checked.
private void CloneCheckedListBox(CheckedListBox source, CheckedListBox target)
{
foreach (int checkedItemIndex in source.CheckedIndices)
{
target.SetItemChecked(checkedItemIndex, true);
}
}
Edit:
I have a User control which I have placed on a TabPage, on that User Control there is a "CheckedListBox", I do need to create a new TabPage with the user entered value on selected(current) TabPage(on User Control)
So, what I have done is, create a new Tab Page, get a Copy of the User Control calling it's "Clone()" method.
In "Clone()" method need to have CheckedListBox cloning feature.
Here is my Cloning Code, which is on User Control...
public SearchMain Clone()
{
SearchMain smClone = new SearchMain();
smClone.txtManufacturers.Text = this.txtManufacturers.Text;
smClone.udPriceFrom.Value = this.udPriceFrom.Value;
smClone.udPriceTo.Value = this.udPriceTo.Value;
smClone.chkOld.Checked = this.chkOld.Checked;
smClone.chkPrx.Checked = this.chkPrx.Checked;
smClone.chkDisc.Checked = this.chkDisc.Checked;
smClone.chkStock.Checked = this.chkStock.Checked;
smClone.chkFirstDes.Checked = this.chkFirstDes.Checked;
smClone.chkFirstPN.Checked = this.chkFirstPN.Checked;
smClone.txtSuppPN.Text = this.txtSuppPN.Text;
smClone.txtManuPN.Text = this.txtManuPN.Text;
smClone.txtManufacturers.Text = this.txtManufacturers.Text;
smClone.meDesAND.Text = this.meDesAND.Text;
smClone.meDesOR.Text = this.meDesOR.Text;
smClone.meDesNOT.Text = this.meDesNOT.Text;
smClone.lbManufacSelected.Items.AddRange(this.lbManufacSelected.Items);
smClone.lbSearchWithIn.Items.AddRange(this.lbSearchWithIn.Items);
**CloneCheckedListBox(this.clbLang, smClone.clbLang);**
// CloneCheckedListBox(this.clbTypes, smClone.clbTypes);
return smClone;
}
You can see correct answere here..
Programatically Checking DataBound CheckListBox
try set
source.DataSource = target.DataSource;
target.DisplayMember = "YourDisplayItem";
target.ValueMember = "YourValueItem";
foreach (int checkedItemIndex in source.CheckedIndices)
{
target.SetItemChecked(checkedItemIndex, true);
}

Categories

Resources