Find specific row attribute jQuery - c#

On my asp.net form, within a table row I add cells and within those cells I add textboxes with an attribute like -
string residentId = (new GUID()).ToString();
string houseId = (new GUID()).ToString();
HtmlTableRow detailRow = new HtmlTableRow();
detailRow.Attributes.Add("residentId", residentId);
detailRow.Attributes.Add("houseId", houseId);
HtmlTableCell dataCell = new HtmlTableCell();
TextBox tb = new TextBox();
tb.Attributes.Add("componentname", "tbMoveInDate");
tb.Attributes.Add("onchange", "updateMoveInDate()";
cell.Controls.Add(tb);
detailRow.Cells.Add(dataCell);
with a possiblility of 100+ rows, all with distinct IDs of course.
within my javascript I have this function -
function updateMoveInDate() {
var MoveInDateEle = $("[componentname*='tbMoveInDate']");
}
at this point MoveInDateEle is a collection of all of those text boxes within the table and
var currentRow = $("[componentname*='tbMoveInDate']").parent().parent();
gives me all of the rows. but not my specific row.
How is it possible to get the specific text box I am working with and the specific resident Id and house Id associated with that control?

Modify the C# code like this:
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
and the js function like:
// obj here refers to the current textbox in the scope
// on which the on-change event had occurred...
function updateMoveInDate(obj) {
var currentRow = $(obj).closest('tr');
}

You could do
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
And
function updateMoveInDate(txt) {
var $txt = $(txt);
var $row = $txt.closest('tr');
var residentId = $row.attr('residentId');
var houseId = $row.attr('houseId');
}

Try this
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
in code behind
string residentId = (new GUID()).ToString();
string houseId = (new GUID()).ToString();
HtmlTableRow detailRow = new HtmlTableRow();
detailRow.Attributes.Add("residentId", residentId);
detailRow.Attributes.Add("houseId", houseId);
HtmlTableCell dataCell = new HtmlTableCell();
TextBox tb = new TextBox();
tb.Attributes.Add("componentname", "tbMoveInDate");
tb.Attributes.Add("onchange", "updateMoveInDate(this)";
cell.Controls.Add(tb);
detailRow.Cells.Add(dataCell);
jQuery:
function updateMoveInDate(args) {
var MoveInDateEle = $(args).closest('tr');
}

Related

Dynamic Controls gets lost durig Postback inside GridView in asp.net C#

I'm facing a very common issue and I've tried almost every solution but none of them solved my problem. I've created a Grid View and I want it to have dynamic columns. Four columns among them must have some controls(textbox,label and checkbox) so I've created it as Template Fields(below code)
TemplateField tf4 = new TemplateField();
tf4.HeaderText = "Sr.No";
CustomerBillingGrid.Columns.Add(tf4);
TemplateField tf1 = new TemplateField();
tf1.HeaderText = "Select";
CustomerBillingGrid.Columns.Add(tf1);
TemplateField tf2 = new TemplateField();
tf2.HeaderText = "Misc";
CustomerBillingGrid.Columns.Add(tf2);
TemplateField tf3 = new TemplateField();
tf3.HeaderText = "Total";
CustomerBillingGrid.Columns.Add(tf3);
Then I've created Bound fields that displays database query result (below code)
if (ds.Tables[0].Rows.Count > 0)
{
int num = 2;
foreach (DataColumn col in ds.Tables[0].Columns)
{
BoundField bf = new BoundField();
bf.HeaderText = col.ColumnName;
bf.DataField = col.ColumnName;
CustomerBillingGrid.Columns.Insert(num, bf);
num++;
}
CustomerBillingGrid.DataSource = ds;
CustomerBillingGrid.DataBind();
}
After than I've Dynamically generated controls for GridView.
protected void GenrateDynamicControls()
{
Label lblSNo = new Label();
lblSNo.ID = "lblSNo";
lblSNo.Text = "1";
Page.Form.Controls.Add(lblSNo);
CheckBox chkSelect = new CheckBox();
chkSelect.ID = "chkSelect";
chkSelect.AutoPostBack = true;
Page.Form.Controls.Add(chkSelect);
TextBox txtMisc = new TextBox();
txtMisc.ID = "txtMisc";
Page.Form.Controls.Add(txtMisc);
TextBox txtTotal = new TextBox();
txtTotal.ID = "txtTotal";
Page.Form.Controls.Add(txtTotal);
}
I've called this method on every Postback
if (!IsPostBack)
{
if (!Convert.ToBoolean(ViewState["DynamicControlsGenrated"]))
{
GenrateDynamicControls();
}
}
The problem I'm facing is that all these dynamic controls gets lost every postback and the second problem is that how to add those dynamically generated controls inside GridView and keep it persistence.
Thanks,
In the case of dynamic control creation inside the grid view, you need to recreate the controls each time on postback and make sure to disable view state mode in grid view.
ViewStateMode="Disabled"

Adding Items to DataGridView from a ListBox to a Single Column

I need to populate a DataGridView with items from a List.
I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).
Currently im Binding the DataGridView like this
dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?
here is your solution,
dgvDataViewer.ColumnCount = 1;
dgvDataViewer.Columns[0].Name = "Language";
string[] row = new string[] { "C#" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C++" };
dgvDataViewer.Rows.Add(row);
row = new string[] { "C" };
dgvDataViewer.Rows.Add(row);
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "HeaderText";
cmb.Name = "Name";
cmb.FlatStyle = FlatStyle.System;
dgvDataViewer.Columns.Add(cmb);
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dgvDataViewer.Rows[0].Cells[1];
dgvcbc.Items.Add("Apple");
dgvcbc.Items.Add("Google");
dgvcbc.Items.Add("Apache");
dgvcbc.Items.Add("Microsoft");
Hope this will help you for your solution.
First you need to build your columns either programmatically or you can use the designer - that is up to you. I will code all of it for the sake of showing the entire example:
private DataGridView dgNew;
public MyForm()
{
InitializeComponent();
MyInitializeComponent();
}
private void MyInitializeComponent()
{
dgNew = new DataGridView();
var txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column1",
Name = "Column1",
DataPropertyName = "Value"
};
dgNew.Columns.Add(txtCol);
txtCol = new DataGridViewTextBoxColumn
{
HeaderText = "Column2",
Name = "Column2",
};
dgNew.Columns.Add(txtCol);
var listOfStrings = new List<string> {"one", "two", "three"};
dgNew.DataSource = listOfStrings.ConvertAll(x => new { Value = x }); ;
dgNew.Location = dg.Location;
dgNew.Parent = this;
this.Load += Form_Load;
}
private void Form_Load(object sender, EventArgs e)
{
// Iterate over the rows, ignoring the header row
foreach (var row in dgNew.Rows.OfType<DataGridViewRow>().Where(a => a.Index != -1))
{
var col1Value = row.Cells["Column1"].Value?.ToString();
var col2Cell = row.Cells["Column2"];
if (col1Value == null) continue;
switch (col1Value)
{
case ("one"):
col2Cell.Value = "row1, col2 val";
break;
case ("two"):
col2Cell.Value = "row2, col2 val";
break;
case ("three"):
col2Cell.Value = "row1, col3 val";
break;
}
}
}

Add checkboxes to a CheckBoxField column

I created a CheckBoxField and added it to my GridView, I would like to know how I can add a checkbox to each row of the new column:
CheckBoxField field = new CheckBoxField();
field.HeaderText = "Export ?";
gv.Columns.Add(field);
I've done similar with a DataGridView (WinForms). This code should help you get a good bit on the way:
// add new checkbox to source
var checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "Move";
checkBoxColumn.Name = "chkMove";
// add new binding
dgCheckBoxes.Columns.Insert(0, checkBoxColumn);
// set values
foreach (DataGridViewRow row in dgCheckBoxes.Rows)
{
if (true)
{
row.Cells["chkMove"].Value = true;
}
else
{
row.Cells["chkMove"].Value = false;
}
}
For a WebForms solution, you should be able to use this Demo from Microsoft: Adding a GridView Column of Checkboxes

Dynamically creating a CheckBoxList

I am trying to create a dynamic menu with a title and group of checkboxes. So the output would be something like this: (pseudocode-ly)
Title 1
-checkbox1 -checkbox2 -checkbox3
Title 2
-checkbox1 -checkbox2 -checkbox3
I can get the Title back just fine, but my checkboxes are not. (See below)
Care
System.Web.UI.WebControls.CheckBoxList
Corporate & Enterprise Solutions
System.Web.UI.WebControls.CheckBoxList
I realize I am returning a DataSet, I just don't know how to handle it.
BusinessUnit bu = new BusinessUnit();
DataSet businessNames = bu.ListBusinessUnitNames();
ArrayList buNames = new ArrayList();
if (businessNames.Tables.Count > 0 && businessNames.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in businessNames.Tables[0].Rows)
{
buNames.Add(row["BSUN_NAME"].ToString());
}
}
int counter = 1;
foreach (string name in buNames)
{
Label lblName = new Label();
lblName.ID = "unitName_" + counter;
lblName.Text = name;
CheckBoxList chkBoxes = new CheckBoxList();
chkBoxes.ID = name + "Programs_" + counter;
foreach (string item in buNames)
{
DataSet buPrograms = bu.ListBusinessUnitPrograms(item);
foreach (DataRow row in buPrograms.Tables[0].Rows)
{
chkBoxes.DataTextField = row[0].ToString();
chkBoxes.Text = chkBoxes.DataTextField;
}
}
programs.InnerHtml += lblName.Text + chkBoxes;
counter++;
}
Here are the mechanics for doing it in code:
ListItem LI1 = new ListItem("aaa");
ListItem LI2 = new ListItem("bbb");
LI1.Selected = true;
LI2.Selected = false;
chkBoxes.Items.Add(LI1);
chkBoxes.Items.Add(LI2);
(Assuming you're using WebForms [aspx])
In your code example, the statement programs.InnerHtml += lblName.Text + chkBoxes; is appending the value of the default .ToString() implementation of the chkBoxes object. To actually add the checkboxes to the page, you will need some sort of container control (such as a Placeholder) on the page, and append your dynamically created control to the container's Controls collection via phPlaceholder.Controls.Add(chkBoxes)

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.

Categories