checkbox in gridview not checked is flase when submit click But when i modify and update button click checked is TRUE
public void addchapselect()
{
TextBox1.Text = "";
for (int i = 0; i < gvChapter.Rows.Count; i++)
{
CheckBox chkbox = (CheckBox)gvChapter.Rows[i].Cells[0].FindControl("chkSelect");
if (chkbox != null)
{
if (chkbox.Checked)
{
TextBox1.Text += Convert.ToString(gvChapter.Rows[i].Cells[0].Text) + ",";
// ItemValueId = ItemValueId + ",";
string Name = Convert.ToString(gvChapter.Rows[i].Cells[1].Text);
}
}
chkbox.Checked = false;
}
if (TextBox1.Text != "")
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1);
}
The reason could be you are binding the Gridview on page_load function.
Bind it inside !IsPostback and it should work.
if (Page.IsPostBack)
{
//bind your grid here.
}
Related
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 have a cascading dropdownlist inside a gridview which contains 5 columns which are ItemsType, ItemList, UnitPrice, Quantity and Total. Selecting ItemsType in 1st dropdownlist will populate items in 2nd dropdownlist i.e. ItemList which is bound to database.
Problem that I am getting is that when I click Edit button, items in 2nd dropdownlist Itemstype isn't selected though I have assigned the selectedValue.
When I ran the webform in debugging mode I saw that though value has been rightly assigned to dropdownlist.selectedvalue, it isn't accepting the value at all.
The weird thing is that when I click the edit button for the second time after 1st debug, items in dropdownlist are selected correctly.
I have used the following
ddlCarriedItems.SelectedValue = SValue;
Though SValue has values of itemlist, SelectedValue displays none.
Here's the code.
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string VRM_id = gv.Cells[0].Text;
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
dc.Vrm_id = Convert.ToInt32(VRM_id);
DataTable dtVRM_CP = vrmbll.edit_VRM_carried_products(dc);
int rowIndex = 0;
if (dtVRM_CP.Rows.Count > 0)
{
for (int i = 0; i < dtVRM_CP.Rows.Count; i++)
{
DropDownList ddlItemsType = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[1].FindControl("ddlItemsType");
DropDownList ddlCarriedItems = (DropDownList)gvCarriedItems.Rows[rowIndex].Cells[2].FindControl("ddlCarriedItems");
TextBox txtItemPrice = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[3].FindControl("txtItemPrice");
TextBox txtItemQty = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[4].FindControl("txtItemQty");
TextBox txtItemTotal = (TextBox)gvCarriedItems.Rows[rowIndex].Cells[5].FindControl("txtItemTotal");
ddlItemsType.SelectedIndex = Convert.ToInt32((dtVRM_CP.Rows[i]["items_type"]).ToString());
int itemstype = ddlItemsType.SelectedIndex;
string SValue = dtVRM_CP.Rows[i]["items"].ToString();
if (itemstype == 1)
{
ddlCarriedItems.SelectedValue =SValue;
}
else if (itemstype == 2)
{
ddlCarriedItems.SelectedValue = SValue;
}
else if (itemstype == 3)
{
ddlCarriedItems.SelectedValue = SValue;
}
else
{ }
txtItemPrice.Text = dtVRM_CP.Rows[i]["items_price"].ToString();
txtItemQty.Text = dtVRM_CP.Rows[i]["items_qty"].ToString();
txtItemTotal.Text = dtVRM_CP.Rows[i]["items_total"].ToString();
if (i != (dtVRM_CP.Rows.Count) - 1 && gvCarriedItems.Rows.Count != (dtVRM_CP.Rows.Count))
{
AddNewRow();
}
rowIndex++;
}
}
}
catch
{ }
}
Ok I've found the problem in my code. The thing is that I had to bind dropdownlist everytime before assigning value to ddlCarriedItems.SelectedValue.
I modified my code as following as per #king.code suggestion:
if (itemstype == 1)
{
DataTable dt = vrmbll.select_raw_materials_production(dc);
ddlCarriedItems.DataSource = dt;
ddlCarriedItems.DataValueField = "ID";
ddlCarriedItems.DataTextField = "Name";
ddlCarriedItems.DataBind();
ddlCarriedItems.Items.Insert(0, new ListItem("----- Select -----", "-1"));
ddlCarriedItems.SelectedValue = SValue;
}
But I have no idea why the previous code worked when I ran debugging for 2nd time.
Okay, as simple as possible, I have a checkboxlist that has autopostback set to true and a OnSelectedIndexChanged. However, every time someone clicks a item in the checkbox, the page refreshes. How do I stop this? I've tried using UpdatedPanel(It kind of work).
<asp:CheckBoxList ID="Regions" runat="server" OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true" DataSourceID="SqlDataSource2" DataTextField="Regions" DataValueField="ID">
</asp:CheckBoxList>
The OnselectedIndexChange displays a div of other checkboxes beside the one checkboxlist.
protected void Regions_SelectedIndexChanged(object sender, EventArgs e)
{
string select = #"Select Facilities from [BulletinBoard].[DMHSAS\290974].[Facilities] ";
int[] ctr = new int[9];
int ctr1 = 0;
int counter = 0;
dFacilities.Style.Add("display", "block");
foreach (ListItem item in Regions.Items)
{
//Response.Write(item.Selected);
if (Regions.SelectedIndex == 0)
{
item.Selected = true;
CheckBoxList1.Visible = true;
counter++;
}
else if (item.Selected)
{
if (select.EndsWith("[Facilities] "))
{
select += "where ";
}
if (select.EndsWith(") "))
{
select += " or ";
}
select += " (Reg_ID = " + Regions.SelectedIndex + ") ";
ctr[ctr1 + 1] = Regions.SelectedIndex;
item.Selected = false;
counter++;
CheckBoxList1.Visible = true;
}
ctr1++;
}
if (counter == 0)
{
CheckBoxList1.Visible = false;
dFacilities.Style.Add("display", "none");
}
ctr1 = 0;
bool all = false;
foreach (int counter1 in ctr)
{
Regions.Items[counter1].Selected = true;
if (Regions.Items[0].Selected == true)
foreach (ListItem item in Regions.Items)
{
if (item.Selected)
{
all = true;
}
else
{
all = false;
break;
}
}
if (all == false)
{
Regions.Items[0].Selected = false;
}
}
You seem to really like the classic .NET postback workflow, but rather than continue down the webforms path of trying to hide postbacks, even though you want them because it makes the logic easier, why not just try sidestepping it just this one time? If, as you say, you want to prevent the page refresh (aka the postback) then there are a few things you can do to prevent it entirely.
At the top of your page:
<style type="text/css">
.hideme
{
display: none;
}
</style>
<script type="text/javascript>
var checkBoxes = document.getElementById("<%= Regions.ClientID %>")
.getElementsByTagName("input");
var cbListIDss = [
"<%= CheckBoxList1.ClientID %>",
"etc"
];
function toggle(i, chkElement)
{
if (chkElement.type == "checkbox") {
if (chkElement.checked) {
var cbElement = document.getElementById(cbListIDss [i]);
cbElement.className = cbElement.className.replace("hideme", "");
break;
}
}
}
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].onClick += toggle(i, checkBoxes[i]);
}
</script>
Edit: Then, in your control, remove these attributes: OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true"
I didn't add the code for modifying the select variable in your postback method, but that can be done in js as well via a hidden input field.
Alternatively, the reason your update panel is not working is because you have
if (Regions.SelectedIndex == 1)
{
select += " where Reg_ID = 1";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
CheckBoxList1.Style.Add("display", "block");
}
if (Regions.SelectedIndex == 2)
{
select += "where Reg_ID = 2";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
// All of these are adding display to CheckBoxList1,
// even though it seems like these should be adding
// the display property to CheckBoxList2, 3, etc.
CheckBoxList1.Style.Add("display", "block");
}
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.
Here's the scenario.
I have checkbox(Name:"Check All" ID:chkItems) and datagridview. And when I click on this checkbox, all checkboxes on the datagridview will also be checked.
I've also added the checkbox column on the grid.
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckBox chk = new CheckBox();
CheckboxColumn.Width = 20;
GridView1.Columns.Add(CheckboxColumn);
Here is the code behind of the checkbox. There is a problem on the row.Cell
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in GridView1.Rows)
{
DataGridViewCheckBoxCell chk = e.row.Cells(0);
if (chk.Selected == false)
{
row.Cells(0).Value = true;
}
}
}
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
instead of
DataGridViewCheckBoxCell chk = e.row.Cell(0);
*EDIT:*I think you really want to do this:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
chk.Value = !(chk.Value == null ? false : (bool) chk.Value); //because chk.Value is initialy null
}
private void setCheckBoxInDataGrid(DataGridView dgv, int pos, bool isChecked)
{
for (int i = 0; i < dgv.RowCount; i++)
{
dgv.Rows[i].DataGridView[pos, i].Value = isChecked;
}
}
This is how I did it
Try this one
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
row.Cells[0].Value = row.Cells[0].Value == false ? true : false;
}
If you are okay with providing a default state to the checkboxes of datagridview on your own i.e either True or False[Do not assign a null state] state(Reason for doing this would be explained in the latter).
Which could be done by the following code,(type in this code when you search for results to be viewed in DataGridView)
dgv is the object of the DataGridView that you are using.
for (int i = 0; i < dgv.RowCount - 1; i++)
{
dgv.Rows[i].DataGridView[0, i].Value = true;
}
Where DataGridView[0, i] indicates 0th column ith row
The Reason for doing this is,On load the checkbox is by default in a null state. The code isn't comparing for null state(Creating a object null reference exception). So, once when u assign it a state either a false or true . It can never undergo into null state.
Type in the following code inside the button_click_event using which you are going to check
for (int i = 0; i < dgv.RowCount-1; i++)
{
if (dgv.Rows[i].Cells[0].Value.ToString() != "")
{
dgv.Rows[i].Cells[0].Value = false;
}
else
{
dgv.Rows[i].Cells[0].Value = true;
}
}
It Worked for me, I hope it does for you.
I tried to select all checkbox or select it mutuality and calculate some value...so wrote this code that's maybe helpful.
foreach (DataGridViewRow item in DGDoc.Rows)
{
if (item.Cells[0].Value == null)
item.Cells[0].Value = "True";
if (bool.Parse(item.Cells[0].Value.ToString()))
{
item.DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(241, 215, 215);
strIDs += "," + item.Cells[1].Value.ToString();
intSumPrice += Int64.Parse(item.Cells[4].Value.ToString());
intSumTax += Int64.Parse(item.Cells[5].Value.ToString());
intSumPay += Int64.Parse(item.Cells[6].Value.ToString());
}
else
{
item.DefaultCellStyle.BackColor = System.Drawing.Color.Empty;
}
}
DGDoc.EndEdit();
1- Create new button.
2- You can use the following code when click checkAll button
3- when click the button it will check all checkboxes in datagridview and when click again it will uncheck all boxes.
private void btncheckall_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvResult.Rows)
{
row.Cells[0].Value = row.Cells[0].Value == null ? false : !(bool)row.Cells[0].Value;
}
}
Note: in some cases you have to click in datagridview first then click the button.
You can check all cells like this:
private void CheckAllCheckboxItemsOnDataGridView(int columnIndex)
{
foreach (DataGridViewRow row in dgFiles.Rows)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[columnIndex];
cell.Value = !(cell.Value == null ? false : (bool)cell.Value);
}
}
You can use method in CheckedChanged event like this:
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
CheckAllCheckboxItemsOnDataGridView(columnIndex: 0);
}
This is my version, which allows a more natural behavior I'd say; if one of the checkboxes is ticked, all checkboxes are ticked as well when selecting all.
How it'll be usefull to you :)
private void BtnSelectAll_Click(object sender, EventArgs e)
{
List<Boolean> chkList = new List<Boolean>();
bool ticked = false;
foreach (DataGridViewRow row in dataGrid.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chkList.Add((bool)chk.Value);
}
if (!chkList.Contains(true))
{
ticked = true;
}
else if (!chkList.Contains(false))
{
ticked = false;
} else
{
ticked = true;
}
foreach (DataGridViewRow row in dataGrid.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = ticked;
}
}