Check Uncheck Checkbox column in Devexpres grid in Winform - c#

Hello developers I am using VS 2010 .I have a dev express grid in which I have a checkbox column.The problem is When i check the checkbox it gets checked but when i move to any other cell or column the checkbox gets automatically unchecked.Till now my code is as follows
if (e.Column.ToString()=="Active" )
{
RepositoryItemCheckEdit edit = UserInfoGridView.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
column = e.Column;
column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
column.Visible = true;
column.VisibleIndex = 3;
column.FieldName = "CheckMarkSelection";
column.Caption = "Active";
column.OptionsColumn.ShowCaption = true;
column.OptionsColumn.AllowEdit = true;
column.OptionsColumn.AllowSize = false;
column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
column.ColumnEdit = edit;
}

Well I found the Answer.........What I did was this
public frmLoad()
{
InitializeComponent();
string DisplayQuery = "Select * from TableName";
MasterDs = SqlHelper.ExecuteDataset(CommonClass.ConnectionString, CommandType.Text, DisplayQuery);
MasterDs.Tables[0].Columns.Add("FLAG", typeof(string));
MainGrid.DataSource = MasterDs.Tables[0];
gridview.PopulateColumns();
gridview.Columns["ID"].VisibleIndex = -1;
gridview.Columns["FLAG"].VisibleIndex = -1;
DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit selectnew = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
gridview.Columns["ColName"].ColumnEdit = selectnew;
selectnew.NullText = "";
selectnew.ValueChecked = "Y";
selectnew.ValueUnchecked = "N";
selectnew.ValueGrayed = "-";
}

It may be because the datasource to witch the grid is bound is not being modified after the check uncheck action. Do you handle the CellValueChanged event of your view to change the property value of an object of your darasource ?
private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
if (e.Column.Name != "Active")
return;
var person = gridView1.GetFocusedRow() as Person;
person.Active = Convert.ToBoolean(e.Value);
}
Or, if you use a DataSet as a Datasource of your grid :
var id = gridView1.GetFocusedRowCellValue("IdColumnName");
var active = gridView1.GetFocusedRowCellValue("ActiveColumnName");
NorthwindDataSet.PersonsRow PersonsRow =
northwindDataSet1.Persons.FindByPersonID(id);
PersonsRow.ACTIVE= Convert.ToBoolean(active);
PS : Not tested

Try like this
string DisplayQuery = "declare #Active bit; set #Active=0; select #Active as Active, * from TableName";

The issue is probably caused by an incorrect underlying type for the column: it should be a bool to work out-of-the-box.
To set the type you may try something like:
MasterDs.Tables[0].Columns[0].DataType = typeof(bool);

I am using Entity Framework 6.1 as the backend with ObjectContext. I had set the database type to be tinyint, which maps to byte when entity framework updates the classes.
Changing the database type to bit and refreshing the entity objects creates the correct boolean type, after which the checkbox shows in DevExpress Winforms correctly.

Related

How to pass value from datagridview to textbox

I am currently working on a system. I have a datagridview with a contextmenu and an edit and delete button on it. I want to pass the value of the selected rows to a textbox when I click the edit on contextmenu.
I have successfully passed the value to the textbox but the only values that show are from the last inputted data to whatever row I click. I don't know how to get the id, can someone please help me fix my problem? :(
Here is my code:
private void BtnEdit_Click(object sender, EventArgs e)
{
frmAddEditStudent frm = new frmAddEditStudent(this);
cn.Open();
cm = new SqlCommand("SELECT s.studentID, s.studentNo, s.Lname, s.Fname, s.MI, s.gender, s.yearLevel, s.section, s.studImage, g.name, g.contactNo, g.address FROM Student s INNER JOIN Guardian g ON g.studentNo = s.studentNo WHERE g.studentNo = s.studentNo AND s.isActive = 'true' AND s.studentID = studentID", cn);
cm.Parameters.AddWithValue("studentID", lblID.Text);
for (int i = 0; i < guna2DataGridView1.Rows.Count; i += 1)
{
frm.btnSave.Enabled = false;
frm.lblTitle.Text = "Edit Student Details";
frm.lblID.Text = guna2DataGridView1.Rows[i].Cells[1].Value.ToString();
frm.txtStudentNo.Text = guna2DataGridView1.Rows[i].Cells[2].Value.ToString();
frm.txtLname.Text = guna2DataGridView1.Rows[i].Cells[3].Value.ToString();
frm.txtFname.Text = guna2DataGridView1.Rows[i].Cells[4].Value.ToString();
frm.txtMI.Text = guna2DataGridView1.Rows[i].Cells[5].Value.ToString();
frm.cboGradeLevel.Text = guna2DataGridView1.Rows[i].Cells[7].Value.ToString();
frm.cboSection.Text = guna2DataGridView1.Rows[i].Cells[8].Value.ToString();
frm.txtGuardianName.Text = guna2DataGridView1.Rows[i].Cells[9].Value.ToString();
frm.txtContactNo.Text = guna2DataGridView1.Rows[i].Cells[10].Value.ToString();
frm.txtAddress.Text = guna2DataGridView1.Rows[i].Cells[11].Value.ToString();
//Load Image
byte[] bytes = (byte[])guna2DataGridView1.Rows[i].Cells[12].Value;
MemoryStream ms = new MemoryStream(bytes);
frm.studImage.Image = Image.FromStream(ms);
//Retrieve gender value to radio button
if (guna2DataGridView1.Rows[i].Cells[6].Value.ToString() == "Male")
{
frm.rbMale.Checked = true;
}
else
{
frm.rbFemale.Checked = true;
}
}
cn.Close();
frm.ShowDialog();
It does not show up the data in the row that I selected, instead it only shows the last row in my database table.
You can get the current row or the selected rows from a datagridview in the following way (I think ID is cell with Index 1):
Console.WriteLine(guna2DataGridView1.CurrentRow.Cells[1].Value.ToString());
foreach (DataGridViewRow loRow in guna2DataGridView1.CurrentRow.SelectedRows)
{
Console.WriteLine(loRow.Cells[1].Value.ToString());
}
But you overwrite the form values in your loop every time.
It seems that your form can only display one row and not a collection.
And what about the command cm??

Adding data-* attributes to a DevExpress MVC gridview cell

I have a standard DevExpress MVCxGridView bound to a DataTable, which is just a bunch of boolean values with the first column "SS" being a string code which is the datakey. I loop through all the columns and dynamically create the gridview columns. The grid that is displayed is a bunch of checkboxes which are options that can be configured.
I have a jquery js file that requires the data-* attributes to be set for these cells in order to inject the necessary functionality. I want to know how to add "data-*" attributes to each of the TD cells. "data-ss" being the datakey in the first column, and "data-wm" being the workmode in the column.
My Razor view code is as follows:
#model System.Data.DataTable
#{
var gv = Html.DevExpress().GridView(
settings =>
{
settings.Name = "gv";
settings.Enabled = true;
settings.KeyFieldName = "SS";
settings.CallbackRouteValues = new { Controller = "Test", Action = "DataBindingPartial" };
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.Settings.VerticalScrollableHeight = 200;
settings.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords;
MVCxGridViewBandColumn currentBand = null;
foreach (System.Data.DataColumn c in Model.Columns)
{
if (c.ColumnName == "SS")
{
DevExpress.Web.ASPxGridView.GridViewColumn column = settings.Columns.Add(c.ColumnName);
column.Caption = "SS";
column.CellStyle.CssClass = "ss_head";
column.HeaderStyle.CssClass = "ss_head_caption";
column.HeaderStyle.Cursor = "pointer";
}
else
{
// Get Column Definition retreives information based on the column name
// definition.ActivityType = "act" if activity or "dg" if DataGathering
// definition.WorkMode = abbreviated name of activity
// definition.Description = long description of activity
var definition =
TestModel.DefinitionColumn.GetColumnDefinition(c.ColumnName);
if (currentBand == null || currentBand.Name != definition.ActivityType)
{
currentBand = settings.Columns.AddBand();
currentBand.Name = definition.ActivityType;
currentBand.Caption = definition.ActivityType == "act" ? "Activity" : "Data Gathering";
currentBand.HeaderStyle.CssClass = String.Format("workmode_col workmode_{0}", definition.ActivityType);
}
DevExpress.Web.ASPxGridView.GridViewColumn column =
currentBand.Columns.Add(c.ColumnName, MVCxGridViewColumnType.CheckBox);
column.Caption = definition.WorkMode;
column.ToolTip = definition.Description;
column.Visible = true;
column.HeaderStyle.Cursor = "pointer";
column.CellStyle.CssClass = String.Format("workmode_{0} workmode_selectable workmode_col", definition.ActivityType);
column.HeaderStyle.CssClass = String.Format("workmode_{0} workmode_col", definition.ActivityType);
column.Width = 35;
}
}
});
var gvBound = gv.Bind(Model);
gvBound.Render();
}
Thank you Mikhail.
Using this I was able to add a settings configuration to set the data-* attributes:
settings.HtmlDataCellPrepared = (sender, e) =>
{
e.Cell.Attributes.Add(
"data-wm",
e.DataColumn.Caption
);
e.Cell.Attributes.Add(
"data-ssco",
e.KeyValue.ToString()
);
};
It is possible to use GridViewSettings.HtmlDataCellPrepared event to assign the required attributes. Check this SO thread.

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate

i have a gridview that creates a new row with a new gridview in it
the method of creating the second gridview is :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "PopExtendedGrid")
{
GridView _gridView = (GridView)sender;
int _rowIndex2 = int.Parse(e.CommandArgument.ToString());
GridView _ChildGrid = new GridView();
Control x = _gridView.Rows[_rowIndex2 + 1].Cells[1].Controls[1];
int Oid = int.Parse(((Label)x).Text);
_ChildGrid.DataSource = hs.GetExtendedGrid(Oid);
_ChildGrid.ID = "ChildGrid";
_ChildGrid.AutoGenerateColumns = false;
_ChildGrid.CssClass = "ChildGridS";
_ChildGrid.HeaderStyle.CssClass = "CreateHead";
BoundField one = new BoundField();
one.DataField = "ItemID";
one.HeaderText = "קוד מוצר";
_ChildGrid.Columns.Add(one);
BoundField two = new BoundField();
two.DataField = "ItemName";
two.HeaderText = "שם מוצר";
_ChildGrid.Columns.Add(two);
BoundField three = new BoundField();
three.DataField = "ItemSize";
three.HeaderText = "גודל מוצר";
_ChildGrid.Columns.Add(three);
GridViewRow tr = new GridViewRow(_rowIndex2 + 2 +10*this.GridView1.PageIndex,-1 , DataControlRowType.EmptyDataRow , DataControlRowState.Normal);
TableCell tc = new TableCell();
tc.ColumnSpan = _gridView.Columns.Count;
tc.Controls.Add(_ChildGrid);
tr.Cells.Add(tc);
if ((DataView)Session["dataSource"] != null)
{
DataView dv = (DataView)Session["dataSource"];
this.GridView1.DataSource = dv;
this.GridView1.DataBind();
}
else
{
if (Session["lvl"].ToString() == "high")
{
PopulateGridViewAdmin();
}
else
{
PopulateGridViewUser();
}
}
this.GridView1.Controls[0].Controls.AddAt(_rowIndex2 + 2, tr);
Session["ChildIndex"] = (_rowIndex2 + 2).ToString();
_ChildGrid.DataBind();
}
}
and i thought that when ever i will need to execute another command or something that is related to the gridview i will remove the row like this:
this.GridView1.Controls[0].Controls.RemoveAt(int.Parse(Session["ChildIndex"].ToString()));
and then repopulate the mastergridview but before i get the chance to do so this error keeps poping up:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
im very frustrated by this and i will take any answer with great gratitude
thanks in advance
You may not need to track ViewState for that control since it's dynamic, so try setting EnableViewState to false and see if that helps.

C# DataGridView with DataSet display issue

I have the following code:
private void Timer1Tick(object sender, EventArgs e)
{
timer_ScanTimer.Enabled = false;
var psc = new ParseScannedCheckNumbers();
if (psc.ParseCheck(_checkData))
{
label_Status.Text = #"Scan Next Check";
var ct = checkTrans.IndividualCheck.NewIndividualCheckRow();
ct.Date = DateTime.Now.ToShortDateString();
var bracct = GetBranchAccountNumber(psc.BankAccountNumber);
if (bracct.Trim().Length == 7)
{
ct.Branch = bracct.Substring(0, 2);
ct.AccountNumber = bracct.Substring(2, 5);
ct.NameOnCheck = GetAccountName(ct.Branch + ct.AccountNumber);
ct.AccountBalance = GetAccountBalance(ct.Branch + ct.AccountNumber);
}
else
{
ct.Branch = Configuration.Branch;
ct.AccountNumber = string.Empty;
ct.NameOnCheck = string.Empty;
ct.AccountBalance = 0;
}
ct.CheckAmount = 0;
ct.BankRoutingNumber = psc.BankRoutingNumber;
ct.BankAccountNumber = psc.BankAccountNumber;
ct.CheckNumber = psc.CheckNumber;
ct.Status = "Entered";
checkTrans.IndividualCheck.Rows.Add(ct);
}
else
{
label_Status.Text = Resources.ScanCheck_ScanFailed;
}
_checkData = string.Empty;
var rs = new RegistrySettings();
if (!rs.ScanChecksContinuous)
{
StopScanning();
label_Status.Text = Resources.ScanCheck_Success;
EditLastRowEntered();
}
label_ChecksScanned.Text = (dgv_Checks.RowCount - 1).ToString();
}
When the timer goes off, I verified that I have received all of the data, then I add it to the dataset. It's being added to the dataset without issue, it's just being seen on the datagridview every time. Sometimes it works, most time it doesn't.
How do I get the datagridview to update when changes are done to the dataset? Am I doing something wrong in the above code?
Thanks! (again)
If you created the dataset and attached it to the DataGridView using the Visual Studio Data Source Configuration Wizard, then you probably have a call to
this.somethingTableAdapter.Fill(this.yourDataSet.someDataTable);
somewhere in your code. This is what actually loads the data from the DataSet into your DataGridView. While calling this method again might not be the 'proper' way to refresh your DGV, it did the job for me.

Fixing FormatException in datagrid view with a checkbox column

I've got a datagrid control bound to BindingList of objects. One of the Properties of the object class is boolean. I have customized that column in the datagridview to be a checkbox type.
Things work correctly when the datagridview loads for the rows that have values brought in from the binding list. However, when the "new entry" line is painted, a System.FormatException is thrown on the checkbox cell.
Exact Error message (relevant portion):
The following exception occurred in the DataGridView:
System.FormatException: Value '' cannot be converted to type 'Boolean'. at System.Windows.Forms.Formatter.FormatObjects....
My searching indicated that this can occur when the true, false, and indeterminate values of the checkbox column are not set.
URL Referencing similar problem to mine:
http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/c29427ff-18be-4fb0-a0a7-d1940e1cd817
However, I have set these values (shown in code below). Beyond this, i can't find any other information relevant to my problem. I'm fairly sure the problem is localized to the use of the checkbox, since, when i change the column type to a simple textbox, i get no exception errors, simply a column of true / false with the "new entry" line showing no value.
DataGridView code:
//
// dataGridView1
//
this.dataGridView1.AllowUserToResizeRows = false;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.NullValue = null;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.columnDescription,
this.columnExpedite,
this.columnId,
this.columnQuantity,
this.columnEntryDate,
this.columnUpdateDate});
this.dataGridView1.Location = new System.Drawing.Point(3, 5);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(1015, 241);
this.dataGridView1.TabIndex = 0;
//
// columnDescription
//
this.columnDescription.DataPropertyName = "Description";
this.columnDescription.FillWeight = 200F;
this.columnDescription.HeaderText = "Description";
this.columnDescription.Name = "columnDescription";
//
// columnExpedite
//
this.columnExpedite.DataPropertyName = "Expedite";
this.columnExpedite.FalseValue = "false";
this.columnExpedite.HeaderText = "Expedited";
this.columnExpedite.Name = "columnExpedite";
this.columnExpedite.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.columnExpedite.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.columnExpedite.TrueValue = "true";
this.columnExpedite.IndeterminateValue = "false";
//
// columnId
//
this.columnId.DataPropertyName = "Id";
this.columnId.HeaderText = "Id";
this.columnId.Name = "columnId";
this.columnId.Visible = false;
//
// columnQuantity
//
this.columnQuantity.DataPropertyName = "Quantity";
this.columnQuantity.HeaderText = "Quantity";
this.columnQuantity.Name = "columnQuantity";
//
// columnEntryDate
//
this.columnEntryDate.DataPropertyName = "EntryDateTime";
dataGridViewCellStyle2.Format = "g";
dataGridViewCellStyle2.NullValue = null;
this.columnEntryDate.DefaultCellStyle = dataGridViewCellStyle2;
this.columnEntryDate.HeaderText = "Entry Date/Time";
this.columnEntryDate.Name = "columnEntryDate";
this.columnEntryDate.ReadOnly = true;
this.columnEntryDate.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.columnEntryDate.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// columnUpdateDate
//
this.columnUpdateDate.DataPropertyName = "UpdateDateTime";
this.columnUpdateDate.HeaderText = "Last Update Date/Time";
this.columnUpdateDate.Name = "columnUpdateDate";
this.columnUpdateDate.ReadOnly = true;
this.columnUpdateDate.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.columnUpdateDate.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
Edit Added:
A couple additional things i've tried:
Attempted using the DefaultValueNeeded event. default value loads when i "touch" the new entry line, but exception fired prior to that, when "new entry" line is actually painting.
Attempted to use
dataGridView1.Columns["columnExpedite"].DefaultCellStyle.NullValue = "false";
with same results.
How do i resolve this exception?
I may be reading this wrong, but this sounds like an order-of-operations issue. I don't see the code where you add the item to the list so I'm not 100% sure on his, but I would guess that you're adding the new object to the list and then modifying the values
You need to ensure that the boolean value is not null. If you're adding a new item,. you will need to populate the value of the object being added before you add it to he list. One possible way to ensure this is to set a default value of either false or true, or set this in the constructor.
Edit - Added
I didn't test this myself, but I'm hoping it will work for you.
Can you hook into the DefaultValuesNeeded event of the DataGridView? That event should fire before the exception is thrown, which should resolve the issue...
Yes.
Try this code:
private void dataGridViewEpizode_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
try
{
e.Row.Cells[22].Value = false;
}
catch (Exception ex)
{
mainForm.staticvar.logger.Write(ex);
}
}

Categories