How to add Attribute in code behind? - asp.net

if (e.Item.ItemType == ListViewItemType.DataItem)
{
HtmlTableRow tr = (HtmlTableRow)e.Item.FindControl("itemTemplate"); //tr of table
if (tr != null)
{
foreach (Control c in tr.Controls)
{
HtmlTableCell cell = (HtmlTableCell)c; //td of table.
if (cell != null)
{
cell.Attributes.Add("onmouseover", "this.class='fontBolding'");
}
}
}
}
Here is part of the template of my listview,and my "fontBolding" is definded in a single .css file and I used it in my current page.
But how can I set the attribute.

Related

Why column count in gridview is 0 when columns are binded dynamically from datatable

I have a gridview which show column count 0 when gridview is directly binded to datasource and columns are not defined statically. I am unable to come up with this problem.
I tried this below code:
foreach (GridViewRow row in gv_services.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < gv_services.Columns.Count; i++)
{
if (row.Cells[i].Controls[0].GetType() == typeof(CheckBox))
{
CheckBox checkBox = row.Cells[i].Controls[0] as CheckBox;
checkBox.Enabled = true;
// checkBox.CheckedChanged += new EventHandler(chck_CheckedChanged);
}
}
}
}
If i understood correctly you are trying to loop through gridview rows and enable checkbox based on your conditions
try this code
foreach (GridViewRow row in yourgridview.Rows)
{
CheckBox myChk = row.FindControl("myControlName") as CheckBox;
if (myChk != null)
{
myChk.Enabled = true;
}
}

How to Create Dynamically Generated TextBoxes in ASP.NET

I have this code which generates TextBoxes in a Table dynamically, I got it from a website:
protected void AddStdBtn_Click(object sender, EventArgs e)
{
CreateDynamicTable();
}
private void CreateDynamicTable()
{
// Fetch the number of Rows and Columns for the table
// using the properties
if (ViewState["Stu"] != null)
Students = (DataTable)ViewState["Stu"];
int tblCols = 1;
int tblRows = Int32.Parse(NoTxt.Text);
// Now iterate through the table and add your controls
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.ID = "txt-" + i.ToString() + "-" + j.ToString();
txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
// Add the control to the TableCell
tc.Controls.Add(txtBox);
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
}
protected void CalculateBtn_Click(object sender, EventArgs e)
{
foreach (TableRow tr in tbl.Controls)
{
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is TextBox)
{
Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
Response.Write("<br/>");
}
}
protected override object SaveViewState()
{
object[] newViewState = new object[2];
List<string> txtValues = new List<string>();
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox)
{
txtValues.Add(((TextBox)cell.Controls[0]).Text);
}
}
}
newViewState[0] = txtValues.ToArray();
newViewState[1] = base.SaveViewState();
return newViewState;
}
protected override void LoadViewState(object savedState)
{
//if we can identify the custom view state as defined in the override for SaveViewState
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[])
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (ViewState["Stu"] != null)
Students = (DataTable)ViewState["Stu"];
if (txtValues.Length > 0)
{
//re-load tables
CreateDynamicTable();
int i = 0;
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox && i < txtValues.Length)
{
((TextBox)cell.Controls[0]).Text = txtValues[i++].ToString();
}
}
}
}
//load the ViewState normally
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}
Now if you examine CreateDynamicTable() function, particularly the line:
int tblRows = Int32.Parse(NoTxt.Text);
you can see that the user can control the number of rows by entering a number in the TextBox NoTxt. When I run this code I get the following error:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
and the error location is in the same line above.
The question is: How can I let the user control the number of rows in the table?
After few days of reading and research, the solution can be done by using Session variables. Store the value obtained in NoTxt.Text as follows for example:
Session["V"] = Int32.Parse(NoTxt.Text);
and retrieve it once you need it.

DataTable Retrieves another DataTable Information?

I Have an Exception in my Live Application..DataTable Retrives another DataTable information..
if (HttpContext.Current.User != null)
{
if (Session["username"] != null)
{
string pageName = Page.Page.AppRelativeVirtualPath.Substring(Page.Page.AppRelativeVirtualPath.LastIndexOf('/') + 1);
DataTable dtFeatures2 = new DataTable();
dtFeatures2.Clear();
objMatermenuPL.usertype = Session["UserType"].ToString();
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
DataView dt = new DataView(dtFeatures2);
dt.Sort = "fld_feature ASC";
if (dtFeatures2 != null)
{
foreach (Control control in leftpanel.Controls)
{
Type ty = control.GetType();
if (ty.Name.ToUpper() == "HTMLANCHOR")
{
int i = dt.Find(control.ID.Substring(3));
if (i < 0 && control.ID.Contains("lnk"))
control.Visible = false;
if (control.ID.Contains("lnk") && control.ID.Substring(3) + ".aspx" == pageName)
{
HtmlAnchor a = (HtmlAnchor)control;
a.Attributes.Add("class", "active");
}
}
}
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
This code we use All most all master pages...If an exception Raise,then it comes directly
this line..
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
Message like : Cannot find column fld_feature.
"dtFeatures2" is Filled With Before Opened Page DataTable Information...
This exception gone after some..It's Working Fine 100%....Some times only shows these exception...What happend Here........

Get value of rows when it s checkbox is checked in radgrid

I have a radgride with checkbox in each rows.I want when i click on button,it checks id of each rows that checked,put into the variable..
I know this code for gridview but I do not know equivalent of this code for radgrid
foreach (GridViewRow rw in grid1.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
id= grid1.Rows[0].Cells[3].Text.ToString();
}
}
if (RadGrid1.Items.Count > 0)
{
foreach (GridDataItem item in RadGrid1.Items)//loops through each grid row
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
//string v= item["ColumnUniqueName"].Text;
string v= item.Cells[3].Text; //accessing cell using its ColumnUniqueName
}
}
}
For more information on Radgrid rows and cell access, check http://www.telerik.com/help/aspnet-ajax/grid-accessing-cells-and-rows.html
Try this: http://www.telerik.com/community/forums/aspnet-ajax/grid/loop-through-radgrid.aspx
foreach(GridItem rw in grid1.Items)
{
CheckBox chkBx = rw.FindControl("Check") as CheckBox ;
if (chkBx != null && chkBx.Checked)
{
string id = rw.Cells[3].Text;
}
}

Bind Dropdownlist with optGroup from sql datasource

I have to bind a Dropdownlist with coutries which should be grouped by region, I have found a sample code from the following link,
http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx?msg=3984074#xx3984074xx
I wanted the country list same as this. But problem is that I want to bind the dropdownlist from sql result. I have tried the following but didn't work,
ddlCountry.DataSource = CountryDtoCollection;
ddlCountry.DataBind();
ddlCountry.Attributes.Add("OptionGroup", "Region");
any one knows any solution for this.
you can write a custom server control and use the data source witch containing the text and region separated by | then split it when use.
[ToolboxData("<{0}:CustomDropDownList runat=server></{0}:CustomDropDownList>")]
public class CustomDropDownList : DropDownList
{
protected override void RenderContents(HtmlTextWriter writer)
{
if (this.Items.Count > 0)
{
bool selected = false;
bool optGroupStarted = false;
string lastOptionGroup = string.Empty;
for (int i = 0; i < this.Items.Count; i++)
{
ListItem item = this.Items[i];
if (item.Enabled)
{
if (lastOptionGroup != item.Text.Split("|")[1])
{
if (optGroupStarted)
{
writer.WriteEndTag("optgroup");
}
lastOptionGroup = item.Text.Split("|")[1];
writer.WriteBeginTag("optgroup");
writer.WriteAttribute("label", lastOptionGroup);
writer.Write('>');
writer.WriteLine();
optGroupStarted = true;
}
writer.WriteBeginTag("option");
if (item.Selected)
{
if (selected)
{
this.VerifyMultiSelect();
}
selected = true;
writer.WriteAttribute("selected", "selected");
}
writer.WriteAttribute("value", item.Value, true);
if (item.Attributes.Count > 0)
{
item.Attributes.Render(writer);
}
if (this.Page != null)
{
this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);
}
writer.Write('>');
HttpUtility.HtmlEncode(item.Text.Split("|")[0], writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
if (optGroupStarted)
{
writer.WriteEndTag("optgroup");
}
}
}
}

Resources