Adding data-* attributes to a DevExpress MVC gridview cell - c#

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.

Related

How to Get Populate Comboboxes Values From Gridview in WinForm?

I want to get grid view data in the StudentRegistrationForm. I have tried many times, but I am unable do this, and I don't understand. Can you tell me how I can get GridView values in my StudentRegistrationForm?
If I comment combo boxes code, then other values are put in StudentRegistrationForm, but I want to show all data in StudentRegistrationForm.
St_Registration obj = new St_Registration();
int St_Id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
obj.txt_name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
obj.txt_fname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
obj.txt_sur_name.Text =dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
obj.txt_email.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
obj.dob_date.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
obj.date_of_registration.Text=dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
obj.txt_address.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
obj.rbtn_male.Checked = true;
obj.rbtn_female.Checked = false;
if (dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString() == "Female")
{
obj.rbtn_male.Checked = false;
obj.rbtn_female.Checked = true;
}
obj.txt_contact.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
obj.cmb_country.Text=dataGridView1.Rows[e.RowIndex].Cells[10].Value.ToString();
obj.cmb_province.Text = dataGridView1.Rows[e.RowIndex].Cells[11].Value.ToString();
obj.cmb_city.Text = dataGridView1.Rows[e.RowIndex].Cells[12].Value.ToString();
obj.txt_pin.Text=dataGridView1.Rows[e.RowIndex].Cells[13].Value.ToString();
obj.ShowDialog();

Passing variable from controller to Devexpress GridView Column EndCallBack JS

I gave a Devexpress GridView which represent addresses. Two cascading combobox (Governorate- Area). When the user choose a Governorate the area combo will filtered according to the Governorate chased. When the user doesn't know the corresponding Governorate for the area, he only start by choosing the area and the governorate combobox will fill with the right governorate.
In index.chtml
<script type="text/javascript">
function governorateCombo_SelectedIndexChanged(s, e) {
areaCode.PerformCallback();
}
function AreaCombo_BeginCallback(s, e) {
e.customArgs['governorateCode'] = governorateCode.GetValue();
}
function areaCombo_SelectedIndexChanged(s, e) {
governorateCode.PerformCallback();
}
function GovernorateCombo_BeginCallback(s, e) {
e.customArgs['areaCode'] = areaCode.GetValue();
}
function GovernorateCombo_EndCallback(s, e) {
benGeoGridView.Refresh();
var bla = '#Session["governorateCode"]';
var item = s.FindItemByValue(bla);
s.SetSelectedItem(item);
}
ComboboxGovernoratePartial.chtml
#Html.DevExpress().ComboBox(settings =>
{
settings.CallbackRouteValues = new { Controller = "benFile", Action = "ComboBoxGovernoratePartial" };
settings.Name = "governorateCode";
settings.Properties.TextField = "governorateName1";
settings.Properties.ValueField = "governorateCode";
settings.Properties.ValueType = typeof(string);
settings.Width = 220;
settings.Properties.EnableSynchronization = DefaultBoolean.False;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
if (Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2) == "ar")
{
settings.RightToLeft = DefaultBoolean.True;
}
settings.Properties.ClientSideEvents.BeginCallback = "GovernorateCombo_BeginCallback";
settings.Properties.ClientSideEvents.SelectedIndexChanged = "governorateCombo_SelectedIndexChanged";
settings.Properties.ClientSideEvents.EndCallback = "GovernorateCombo_EndCallback";
}).BindList(Model).Bind(ViewData["governorateCode"]).GetHtml()
In controller:
public ActionResult ComboBoxGovernoratePartial()
{
string areaCode = (Request.Params["areaCode"] != null) ? Request.Params["areaCode"] : "-1";
List<governorateName> governorateNames = new List<governorateName>();
governorateMaster governorateMaster = new governorateMaster();
if (areaCode != null)
{
Session["governorateCode"] = Masters.areaMasters.First(a => a.areaCode == areaCode).governorateCode; ;
ViewData["governorateCode"] = Masters.areaMasters.First(a => a.areaCode == areaCode).governorateCode;
governorateNames = Masters.governorateNames.Where(a => a.langCode.ToLower() == Thread.CurrentThread.CurrentCulture.Name.Substring(0, 2)).ToList();
}
return PartialView(governorateNames.ToList());
}
When the user choose the area, (in js) I call perform call back for the governorate combobox that the controller pick up the right governorate to populate in the governorate combobox. The problem is that when I send the governorate code in a ViewData it is always null. In a Session varible, the value of it is the one at page load not the updated one in the controller.
Any suggestion ?
Sorry for your time guys
For that, you can try:
TempData["yourVar"]

Setting a default value of null to the cell in the dev express grid if the user has not entered a value during inline editing

This is a partial view called from the index.
In the model the JobStatusSortOrder is set as a nullable double.
Here if the user does not enter any value during inline editing, how can i set the value to null by default.
I have tried looking for options like default text and I cant find any to help me.
Could someone please help me with this? Thanks!
#model MyProject.Web.ViewModels.ProjectStatusListViewModel
#using MyProject.Data.Models;
#using System.Web.UI.WebControls;
#using DevExpress.Web.Mvc.UI;
#using DevExpress.Web.ASPxEditors;
#using DevExpress.Web.Mvc;
#using DevExpress.Web.ASPxGridView;
#{
Html.EnableClientValidation(true);
var grid = Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvProjectStatus";
settings.KeyFieldName = "JobStatusID";
settings.Width = Unit.Pixel(1080);
settings.CallbackRouteValues = new { Controller = "Maintenance", Action = "ProjectStatusMasterPartial" };
settings.ClientSideEvents.BeginCallback = "function(s,e){e.customArgs['id'] = '" + ViewContext.RouteData.Values["JobStatusID"] + "'}";
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Maintenance", Action = "JobStatusInlineAddNewPartial" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Maintenance", Action = "JobStatusInlineEditPartial" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Maintenance", Action = "JobStatusInlineDeletePartial" };
settings.SettingsEditing.Mode = GridViewEditingMode.Inline;
settings.SettingsBehavior.ConfirmDelete = true;
//Command column
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.Caption = "Actions";
settings.CommandColumn.Width = 60; //Width is actually 100 not 60
//for filtering
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowFilterRowMenu = true;
settings.CommandColumn.ClearFilterButton.Visible = true;
settings.Columns.Add(column =>
{
column.FieldName = "JobStatusID";
column.Caption = "JobStatusID";
column.Visible = false;
});
settings.Columns.Add(column =>
{
column.FieldName = "SiteID";
column.Caption = "SiteID";
column.Visible = false;
});
settings.Columns.Add(column =>
{
column.FieldName = "JobStatusName";
column.Caption = "Status Description";
column.Settings.AllowAutoFilter = DefaultBoolean.True;
});
settings.Columns.Add(column =>
{
column.FieldName = "JobStatusCurrent";
column.Caption = "Is Current";
column.ColumnType = MVCxGridViewColumnType.CheckBox;
column.Settings.AllowAutoFilter = DefaultBoolean.False;
});
settings.Columns.Add(column =>
{
column.FieldName = "JobStatusSortOrder";
column.Caption = "Sort Order";
column.Settings.AllowAutoFilter = DefaultBoolean.False;
});
});
}#grid.Bind(Model.JobStatus.ToList()).GetHtml()
Try this:
#{
Html.EnableClientValidation(true);
var grid = Html.DevExpress().GridView(
settings =>
{
//your code
//Add this code to initialize the rows for a New Row
settings.InitNewRow = (sender, e) =>
{
e.NewValues["JobStatusSortOrder"] = 0; // set the default value as 0
};
});
}#grid.Bind(Model.JobStatus.ToList()).GetHtml()
Since it is a numeric type, any empty value in the DevExpress grid should be equal to null in your data structure. Can't you just check the edited values for an empty string, and set them to null before sending to your data layer?

Check Uncheck Checkbox column in Devexpres grid in Winform

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.

How can i set up all the data's in the textbox

first of all there is a searchbox form and a view form. after passing the value of the id in the searchbox, it should return all the values that matches with the id of that person after the textchange method occured. but it doesn't display a single value on the textboxes. here is my code
public void first_tab_search(string key)
{
key = txtSearch.Text;
var first = from a in dbcon.personal_informations where a.last_name == key select a;
foreach (var setThem in first)
{
txtsurname.Text = setThem.last_name;
txtfirstname.Text = setThem.first_name;
txtmiddlename.Text = setThem.middle_name;
txtID.Text = setThem.userid;
txtweight.Text = setThem.weight;
txttin.Text = setThem.tin;
txtsss.Text = setThem.sss;
txtaeno.Text = setThem.agency_employee_no;
txtbloodtype.Text = setThem.blood_type;
txtcitizenship.Text = setThem.citizenship;
txtcivilstatus.Text = setThem.civil_status;
txtcpno.Text = setThem.cell_no;
txtdob.Text = setThem.datetime_of_birth.ToString();
txtemail.Text = setThem.email_address;
txtgender.Text = setThem.sex;
txtgsis.Text = setThem.gsis_id;
txtheight.Text = setThem.height;
txtnameext.Text = setThem.name_ext;
txtpagibig.Text = setThem.pagibig_id;
txtpermaaddr.Text = setThem.permanent_address;
txtpermatelno.Text = setThem.permanent_telno;
txtpermazip.Text = setThem.permanent_zipcode;
txtphilhealth.Text = setThem.philhealth;
txtpob.Text = setThem.place_of_birth;
txtresidentialaddr.Text = setThem.residential_address;
txtresitelno.Text = setThem.residential_telno;
txtresizip.Text = setThem.residential_zipcode;
txtweight.Text = setThem.weight;
}
}
You have a whole host of problems going on here.
You pass a key into the method, and then immediately overwrite it with the contents of your search box.
Your search could return more than one result, and therefore your code is looping through each result and overwriting the output values with the last returned row. Use += rather than + in your loop, i.e.
txtsurname.Text += setThem.last_name;
Your code is currently case sensitive, this may be the desired approach but might not be.

Categories