Build Treeview with parent, child tables - asp.net

I am building treeview using asp.net 2.0/3.5 from master detail table.
ParentTable Value
---ChildTable Value
---GrandChildTable1 Node
---GrandChildTable1 Value
---GrandChildTable2 Node
---GrandChildTable1 Value
I have created something like this to populate node values. But I am not sure how to display GrandChildNode and values. Could you please let me know if there are any ideas?
Thank you for any help.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
switch (e.Node.Depth)
{
case 0:
GetParentTableValues(e.Node);
break;
case 1:
GetChildTableValues(e.Node);
break;
case 2:
}
}

Here is my solution:
string NodeText = string.Empty;
string NodeKey = string.Empty;
TreeRolesList.Nodes.Clear();
DataTable dtEnqRoles = bllENQRolesMaster.GetENQRolesMasterByRolesDetail();
if (dtEnqRoles.Rows.Count > 0)
{
for (int i = 0; i < dtEnqRoles.Rows.Count; )
{
NodeText = dtEnqRoles.Rows[i]["RoleDescriptionMaster"].ToString().Trim();
NodeKey = dtEnqRoles.Rows[i]["RoleMasterID"].ToString();
TreeNode pNode = new TreeNode(NodeText, NodeKey);
TreeRolesList.Nodes.Add(pNode);
foreach (DataRow dr in dtEnqRoles.Select("RoleMasterID = " + NodeKey))
{
TreeNode childNode = new TreeNode(dr["RoleDescriptionDetail"].ToString().Trim(), dr["RoleDetailID"].ToString());
pNode.ChildNodes.Add(childNode);
i++; //incrementing the outer loop here
}
}
TreeRolesList.ExpandAll();
}

Related

how to get value from dynamically created textbox in asp.net

hi i'm Cannot get value dynamically created textbox and save into database. plz help
his is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error
protected void btnAtt_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
for (int i = 0; i < query.Count(); i++)
{
Label lblatt = new Label();
lblatt.ID = query[i].AttributeName;
lblatt.Text = query[i].AttributeName + " : ";
lblatt.CssClass = "control-label";
TextBox txtatt = new TextBox();
txtatt.ID = "txtatt"+i;
txtatt.Attributes.Add("runat", "server");
txtatt.Text = String.Empty;
txtatt.CssClass = "form-control input-sm";
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(lblatt);
HtmlTextWriterTag.Br.ToString();
Place1.Controls.Add(txtatt);
HtmlTextWriterTag.Br.ToString();
}
}
protected void lbtnSave_Click(object sender, EventArgs e)
{
int DPLID = int.Parse(DPLCategory.Text);
var query = (from p in database.tbl_Attributes
where p.ProductTypeId_FK == DPLID
select new
{
p.Attribute_Id,
p.AttributeName,
p.ProductTypeId_FK,
}).ToArray();
int LastId = database.tbl_Products.Max(p => p.ProductId);
for (int i = 0; i < query.Count(); i++)
{
database.tbl_ProductValue.Add(new Models.tbl_ProductValue()
{
ProductId_FK = LastId,
AttributeID_FK = query[i].Attribute_Id,
ProductValue = ??,
});
database.SaveChanges();
}
}
plz help me for how to get textbox?
I haven't worked with WebForms in a while but you can access the controls by their IDs like this:
ProductValue = ((TextBox)FindControl("txtatt" + i)).Text;

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.

Change the visibility of label within a datalist

How can I change the visibility of a label with a datalist using asp.net and C#-4.0 ? I tried the following code but unfortunately it is not working:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
viewall();
}
protected void viewall()
{
MySqlCommand objacess = new MySqlCommand();
objacess.CommandText = "select * from product_tbl ";
DataTable dobj = new DataTable();
dobj = objDataAccess.GetRecords(objacess);
for (int i = 0; i < dobj.Rows.Count; i++)
{
string d = dobj.Rows[i]["pdiscount"].ToString();
int di = Convert.ToInt32(d);
if (di > 0)
{
Label lbldisc = (Label)DataList1.FindControl("lbl_discount");
lbldisc.Visible=true;
}
}
DataList1.DataSource = dobj;
DataList1.DataBind();
}
When I try this I receive the following Error:
Error : Object reference not set to an instance of an object.
dear friend your code is not finding the lable control thats why its giving you this error and all our databound countrol are working on then indexes so change you this line
Label lbldisc = (Label)DataList1.FindControl("lbl_discount");
to the following
Label lbldisc = (Label)DataList1.item[i].FindControl("lbl_discount");
you need to write hide code after binding the values.
//bind value to datalist
DataList1.DataSource = dobj;
DataList1.DataBind();
//after binding hide the label
for (int i = 0; i < dobj.Rows.Count; i++)
{
string d = dobj.Rows[i]["pdiscount"].ToString();
int di = Convert.ToInt32(d);
if (di > 0)
{
Label lbldisc = (Label)DataList1.FindControl("lbl_discount");
lbldisc.Visible=true;
}
}

Change row color of gridview by database Values

I am making a application in asp.net which shows the values in gridview from the database.In database i am having a colmn named as StatusId which has a value of 1 or 2 or 3.
I tried to show the grid view rows in different color by their statusId values. But it never works. How can i do it in asp.net.
Here is my code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Connection.Open();
SqlCommand Command1 = Connection.CreateCommand();
Command1.CommandText = "Select statusColor from status where statusId=(Select statusId from fileInfo where userId=(Select userId from userInfo where email='" + Session["email"].ToString() + "'))";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
using (SqlDataReader reader = Command1.ExecuteReader())
{
while (reader.Read())
{
statusId = reader["statusColor"].ToString();
}
GridView1.RowStyle.BackColor = Color.FromName(statusId);
}
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.Green;
}
SqlCommand com = new SqlCommand("gridcolor", Connection);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#statusId", statusId);
com.Parameters.Add("#statusColor", SqlDbType.NVarChar, 30);
com.Parameters["#statusColor"].Direction = ParameterDirection.Output;
com.ExecuteNonQuery();
string msg = (string)com.Parameters["#statusColor"].Value;
Connection.Close();
}
What is the mistake i am doing here?
EDIT
I have the color codes which are stored in the database named as statusColor. I have to apply those color to these status.
You have statusId having values 1,2,3 and you are passing to Color.FromName which and 1,2,3 are not names of color you can use switch to assign different colors based on statusId .
Color rowColor = Color.Red;
switch(statusId)
{
case 1:
rowColor = Color.Green;
break;
case 2:
rowColor = Color.White;
break;
case 3:
rowColor = Color.Blue;
break;
}
GridView1.RowStyle.BackColor = rowColor ;
You are doing it the wrong way. You have to databind your gridview on either page load or a custom event (say click of a button) & not rowDataBound event. This event occurs when your row is bound with data & you want to change some attributes for each row (as in your case).
You can use Gridview DataBound event to assign colors in following way
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Fetch status Id for current row
int statusId= Convert.ToInt32(DataBinder.Eval(e.Row.DataItem,"UnitsInStock"));
switch (statusId)
{
case (1):
e.Row.BackColor= System.Drawing.Color.Green;
break;
// other cases follow the same
}
}
}
Put the databinding code in either pageLoad or button click event.
protected void grdMyQ_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < grdMyQ.Rows.Count; i++)
{
if (grdMyQ.Rows[i].Cells[13].Text.ToUpper() == "DISCHARGED_PROCESS")
{
grdMyQ.Rows[i].BackColor = Color.Red;
}
}
}

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

Resources