I want to get the values of the selected checkbox in a RadGrid.
I have a radgrid, textbox and a button as follows:
this._RadAjaxPanel.Controls.Add(RadGrid1);
this._RadAjaxPanel.Controls.Add(TextBox1);
this._RadAjaxPanel.Controls.Add(Buton1);
The radgrid id is set to RadGrid1 and
Button1.OnClientClick = "GetSelectedItems("+ this._RadGrid1 +")";
On click of the button a javascript is called where I want to know which rows have been selected.
The javascript function is as follows but it is not correct:
function GetSelectedItems(grid) {
var selectedRows = grid.get_selectedItems();
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
var cell = grid.getCellByColumnUniqueName(row, "CategoryID")
//here cell.innerHTML holds the value of the cell
}
}
Please let me know how can I get the selected rows.
Here is how to get whether or not a checkbox is selected. I am using a GridTemplateColumn with a CheckBox as the ItemTemplate, which Telerik always suggests using over the GridCheckBoxColumn.
The trick is to get the inner HTML in the cell, and parse out the name of the control. The cell value will be something like id=cbxRow where the CheckBox control's ID is cbxRow like in the below example.
JavaScript:
var grid = $find("RadGrid1");
var masterTableView = grid.get_masterTableView();
var selectedRows = masterTableView.get_selectedItems();
for (var i = 0; i < selectedRows.length; i++) {
var cellCB = masterTableView.getCellByColumnUniqueName(row, "CB");
var innerCB = cellCB.innerHTML;
var locId = innerCB.indexOf("id=");
var locIdEnd = innerCB.indexOf("\" ", locId);
var idVal = innerCB.substr(locId + 4, locIdEnd - locId - 4);
var cbx = document.getElementById(idVal);
if (cbx.checked) {
alert("The checkbox is checked!");
}
else {
alert("The checkbox is not checked!");
}
}
ASPX:
<telerik:GridTemplateColumn UniqueName="CB" ...>
<ItemTemplate>
<asp:CheckBox ID="cbxRow" runat="server">
</ItemTemplate>
</telerik:GridTemplateColumn>
I have tried the following, which solved my issue:
this._Button1.Attributes.Add("OnClick", "GetSelectedItems('" + _RadGrid1.ClientID + "');return false;");
Related
I Created a application which will map the data and save the Data fields. For that first row in my GridView I added new HearerRow with dropdownlist.
Below is my code which I have attached.
My HTML Page code:
<asp:GridView ID="gvDataMapping" runat="server" AutoGenerateColumns="false">
</asp:GridView>
And Code Behind:
for (int i = 0; i < dtValues.Columns.Count; i++)
{
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
boundfield.HeaderText = dtValues.Columns[i].ColumnName.ToString();
gvDataMapping.Columns.Add(boundfield);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
DropDownList ddlFieldValues;
TableCell HeaderCell;
foreach (DataColumn dc in dtValues.Columns)
{
ddlFieldValues = new DropDownList();
ddlFieldValues.ID = "FieldValues";
ddlFieldValues.DataSource = (DataTable)Session["WorkItemTypeField"];
ddlFieldValues.DataTextField = "FieldName";
ddlFieldValues.DataValueField = "FieldID";
ddlFieldValues.DataBind();
ddlFieldValues.Items.Insert(0, new ListItem("", "0"));
HeaderCell = new TableCell();
HeaderCell.Controls.Add(ddlFieldValues);
HeaderGridRow.Cells.Add(HeaderCell);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
gvDataMapping.Visible = true;
lblDataMapping.Visible = true;
gvDataMapping.Controls[0].Controls.AddAt(1, HeaderGridRow);
See the Click here to view screen displays the output of above code . While clicking Save am not getting the GridView Header DropDowmList its showing null using below code.
GridViewRow gvrow2 = gvDataMapping.HeaderRow;
foreach (GridViewRow row in gvDataMapping.Rows)
{
for (int i = 0; i < gvDataMapping.Columns.Count; i++)
{
String header = gvDataMapping.Columns[i].HeaderText; //gets column name
DropDownList cellText = ((DropDownList)gvrow2.Cells[i].FindControl("FieldValues")); //Not getting the DDL returns null
}
}
How to get the GridView Header row dropdownlist values in Save click event?
No guarantees, because I haven't tried this myself, but what about this code?
GridViewRow gvrow1 = GrdDynamic1.HeaderRow;
foreach (GridViewRow row in GrdDynamic1.Rows)
{
for (int i = 0; i < GrdDynamic1.Columns.Count; i++)
{
String header = GrdDynamic1.Columns[i].HeaderText;
DropDownList cellText = ((DropDownList)gvrow1.Cells[i].FindControl("FieldValues"));
}
}
It looks as if you're looking for the drop down list in the right column, but not the right row: you're looking in the data row, rather than the header row gvrow1.
Ok here is the scenario. I have created a completely data driven Radgrid with only 2 static buttons on the page, Save and Cancel. The Radgrid is created dynamically, as well as all the data in the grid (from MS SQL). Here is the tricky part, I have a template column that will contain a control. The type of control is determined again by the data in SQL. I.e., data is 6, I need to return a RadTextBox populated with data from SQL, 5 = RadComboBox, also populated... you get the jist. I have a total of 50 records, so I have around 50 controls, all populated with data which can change and be saved. That is the hard part. I have been stuck for 2 days trying to figure out how to get to the RadGrids cell level, find the control, determine what type of control it is, retrieve the lastest data from that control and save it back out to the Database. The code works, I just need help finding the controls and saving the data...
I need to hit the Save button, which in turn gets all the data and saves it to db. I cannot show you all my code because the codebehind is close to 600 lines. but I will demonstrate with one.
I am giving the controls IDs based on a unique value from that row, so ID="c" = x where x is the unique value.
page.aspx
<form id="formUnionActivityProtestor" runat="server">
<asp:HiddenField ID="hiCaseId" runat="server" />
<asp:HiddenField ID="hiCaseSequence" runat="server" />
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" ScriptMode="Release">
</telerik:RadScriptManager>
<div id="headDiv">
<h2>Blah blah blah</h2>
<h3>blah zeyblah</h3>
<telerik:RadButton runat="server" ID="btnSaveUA" CausesValidation="true" OnClick="btnSaveUA_Click"
Text="Save Union Activity" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
<telerik:RadButton runat="server" ID="btnCancel" OnClientClicking="ReadOnly"
Text="Cancel Changes" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
</div>
<hr />
<div id="gridContainer" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</div>
</form>
page.aspx.cs
protected void Page_Init(object sender, System.EventArgs e)
{
radgrid = new RadGrid();
radgrid.ID = "radgrid";
radgrid.PreRender += new EventHandler(radUAGrid_PreRender);
PlaceHolder1.Controls.Add(radgrid);
this.radgrid.NeedDataSource += new GridNeedDataSourceEventHandler(this.grid_NeedDataSource);
radgrid.ItemDataBound += new Telerik.Web.UI.GridItemEventHandler(this.radgrid_ItemDataBound);
radgrid.MasterTableView.DataKeyNames = new string[] { "q_SortValue" };
radgrid.MasterTableView.AutoGenerateColumns = false;
radgrid.MasterTableView.ShowHeader = false;
radgrid.BorderColor = System.Drawing.Color.Gray;
GridBoundColumn boundColumn;
boundColumn = new GridBoundColumn();
boundColumn.ItemStyle.Width = 600;
boundColumn.ItemStyle.CssClass = "prompt";
boundColumn.DataField = "q_Prompt";
radgrid.MasterTableView.Columns.Add(boundColumn);
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new TemplateColumn("q_QuestionnaireTypeID");
//templateColumn.ItemStyle.Width = 0;
templateColumn.DataField = "q_QuestionnaireTypeID";
templateColumn.UniqueName = "q_QuestionnaireTypeID";
radgrid.MasterTableView.Columns.Add(templateColumn);
boundColumn = new GridBoundColumn();
boundColumn.Display = false;
boundColumn.ItemStyle.CssClass = "hidecol";
boundColumn.DataField = "t_QuestionnaireTypeDescription";
radgrid.MasterTableView.Columns.Add(boundColumn);
}
public partial class TemplateColumn : System.Web.UI.Page ,ITemplate //adding template fields
{
string fieldName = "";
int controlTypeID = 0;
DataTable dt;
int counter = 1;
UnionActivity refMgr = new UnionActivity(Global.ICEConnectionString);
public TemplateColumn(string fieldName)
{
this.fieldName = fieldName;
}
public int getQuestionTypeID(int count)
{
int k = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == count
select (Int32)dr["q_QuestionnaireTypeID"]).FirstOrDefault();
return k;
}
public void InstantiateIn(Control container)
{
if (counter == 1)
{
dt = UnionActivityDataTable.dt;
}
controlTypeID = getQuestionTypeID(counter);
if (controlTypeID == 5)
{
int QID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceID"]).FirstOrDefault();
int QQID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceQuestionID"]).FirstOrDefault();
string answer = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (string)dr["a_Answer"]).FirstOrDefault();
DataTable dt1;
dt1 = getDropDownList(QID, QQID);
RadComboBox cb = new RadComboBox();
foreach (DataRow row in dt1.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["DisplayValue"].ToString();
item.Value = row["DDID"].ToString();
if (answer == item.Text)
{
cb.SelectedValue = item.Value;
}
cb.Items.Add(item);
item.DataBind();
}
string x = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select Convert.ToString((int)dr["a_QuestionnaireInstanceQuestionID"])).FirstOrDefault();
cb.ID = "c" + x;
container.Controls.Add(cb);
}
}
DataTable getDropDownList(int QID, int QQID)
{
DataTable dt2 = new DataTable();
try
{
using (refMgr)
{ //retrieving qicr_QuestionnaireInstanceCaseReferenceID
using (DataTable getDropDownData = refMgr.DynamicDropDownData(QID, QQID))
{
if (getDropDownData != null)
{
dt2 = getDropDownData;
}
}
}
}
catch (Exception ex)
{
}
return dt2;
}
}
after page load I look at the source and this is the insert for the combobox...
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;">
<input name="radgrid$ctl00$ctl22$c12" type="text" class="rcbInput radPreventDecorate" id="radgrid_ctl00_ctl22_c12_Input" value="Kiosk" readonly="readonly" />
</td>
I need to attach a method to the save button, but I dont know the first place to start. Telerik is good about getting the page built dynamically, but not saving the data back out. (or even finding the controls...)
I have seen something like this done for survey generation. The only difference is that it wasn't using a Grid. Is there a reason why you need to use a grid rather than just dynamically building the controls on the page?
I can suggest a way so that you can easily obtain the values from dynamic controls.
You can introduce an interface that all your survey controls need to implement.
interface ISurveyControl
{
// expose some common properties
int QuestionID {get; set;}
object Value {get; set;}
// and others as required
}
Then create an extension for every type of control that you need in your survey
public class SurveyTextBox : RadTextBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return Text; }
set { Text = value.ToString(); }
}
}
public class SurveyComboBox : RadComboBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return SelectedValue; }
set { SelectedValue = value.ToString(); }
}
}
Make sure you use these extended controls when building the survey and populate the common properties correctly.
Then all you need is a helper function to find all ISurveyControl controls from a container, regardless of whether it's a grid or a page.
List<ISurveyControl > FindSurveyControls(Control container)
{
// you can use linq to find all ISurveyControl within the container
// you may need to make this recursive as well
}
You can then iterate through the controls on save, knowing that they hold enough information such as the QuestionID and so on.
Code:
DataSet ds = _dalEquipmentwiseCheckList.getEquipmentName();
ddEquipmentName.DataSource = ds.Tables[0].DefaultView;
ddEquipmentName.DataTextField = ds.Tables[0].Columns[1].ToString();
ddEquipmentName.DataValueField = ds.Tables[0].Columns[0].ToString();
ddEquipmentName.DataBind();
What I want is: when selecting a row in the GridView, the corresponding equipment name
should get selected in the dropdown list:
var selectRow = MyGridView.SelectedRow;
ddEquipmentName.SelectedValue = selectRow.Cells[2].Text;
****//this is giving me error****
Selected value does not work in this way. Try this:
ddEquipmentName.SelectedIndex = ddEquipmentName.Items.IndexOf(ddEquipmentName.Items.FindByText(selectRow.Cells[2].Text));
You can try :
GridViewRow selectRow = MyGridView.SelectedRow;
ddEquipmentName.selectedItem.Text = selectRow.Cells[2].Text;
void setDataContext()
{
var selectRow = GridEquipmentChechList.MyGridView.SelectedRow;
if (selectRow != null)
{
txtECNumber.Text = selectRow.Cells[1].Text;
**ddEquipmentName.SelectedIndex = ddEquipmentName.Items.IndexOf(ddEquipmentName.Items.FindByText(selectRow.Cells[2].Text));**
**ddDescription.SelectedIndex = ddDescription.Items.IndexOf(ddDescription.Items.FindByText(selectRow.Cells[3].Text));**
}
}
I have a grid view, which contains a dropdownlist and a panel that i want to make invisible and visible by the selected value of the dropdownlist.
The javascript code which works when not used with the gridview is:
function showPannel(panelId,dropdownId ) {
var panel = document.getElementById(panelId);
var dropDown = document.getElementById(dropdownId);
if (dropDown.options[dropDown.selectedIndex].value = 'Diesel Deals') {
panel.className = "visibleDiv";
}
else{
panel.className = "hiddenDiv";
}
}
i'm passing the panelId and dropdownlist id from here:
if (e.Row.RowType == DataControlRowType.DataRow)
{
Panel p = (Panel)e.Row.FindControl("Panel1");
DropDownList t1 = (DropDownList)e.Row.FindControl("DropDownList1");
t1.Attributes.Add("onchange",
string.Format("javascript:showPannel('{0}', '{1}')",p.ClientID, t1.ClientID ));
}
but it is not working. The function is getting called, but its giving undefined when dropDown.options[dropDown.selectedIndex].value is alerted.
I tried to do
Gridview1 = document.getElementById('<%=GridView1.ClientID%>');
var cell = Gridview1.rows[0].cells[2];
var dropdownlist = cell.childNodes[0];
var dropdownSelectedValue = dropdownlist.options[dropdownlist.selectedIndex].value;
alert(dropdownSelectedValue);
but its not working either.
Please help
Thanks
Panel p = (Panel)e.Row.FindControl("Panel1");
DropDownList t1 = (DropDownList)e.Row.FindControl("DropDownList1");
string p_id = GridView1.ClientID + "_" + p.ClientID;
string ddL_id = GridView1.ClientID + "_" + t1.ClientID;
t1.Attributes.Add("onchange",
string.Format("javascript:showPannel('{0}', '{1}')", p_id, ddL_id ));
thanks for the hint about rendering id
I am creating an application where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
Put a placeHolder on your form with the ID placeHolder and add the following code to your Page_Load():
CheckBoxList cbList = new CheckBoxList();
for (int i = 0; i < 10; i++)
cbList.Items.Add(new ListItem("Checkbox " + i.ToString(), i.ToString()));
placeHolder.Controls.Add(cbList);
This will add 10 CheckBox objects within your CheckBoxList(cbList).
Use the following code to examine each CheckBox object within the CheckBoxList
foreach(ListItem li in cbList.Items)
{
var value = li.Value;
var text = li.Text;
bool isChecked = li.Selected;
}
The placeholder is used to add the CheckBoxList to the form at runtime, using a placeholder will give you more control over the web page where the CheckBoxList and its items will appear.
Here is an example
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
chkList.ID = "ChkUser";
chkList.AutoPostBack = true;
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
this.Form.Controls.Add(pUser);
At code behind you can create new ASP.NET Controls and you can add these controls to your page. All you need to do is to create new CheckBoxList Object and add ListItems to it. Finally, you need to add your CheckBoxList to your Page.
// Create CheckBoxList
CheckBoxList list= new CheckBoxList();
// Set attributes for CheckBoxList
list.ID = "CheckBoxList1";
list.AutoPostBack = true;
// Create ListItem
ListItem listItem = new ListItem();
// Set attributes for ListItem
listItem .ID = "ListItem1";
// Add ListItem to CheckBoxList
list.Items.Add(listItem );
// Add your new control to page
this.Form.Controls.Add(list);