How to retrieve value from dynamic text box using C#? - c#

I am using tree view in my web application, but I am using dynamic input text box when tree view data bind. The code is:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
tables = node[0].ChildNodes[0].SelectNodes("col[#text='" + ds.Tables[0].Rows[i]["ModuleName"].ToString() + "']");
TreeNode MyRoot = new TreeNode();
string GUID = Guid.NewGuid().ToString();
MyRoot.Text = " " + ds.Tables[0].Rows[i]["ModuleName"].ToString() + " " + "<input type='text' id='" + GUID + "' />";
MyRoot.Value = ds.Tables[0].Rows[i]["ModuleName"].ToString();
if (RootNode != ds.Tables[0].Rows[i]["ModuleName"].ToString())
{
tv_GetMenu.Nodes.Add(MyRoot);
RootNode = ds.Tables[0].Rows[i]["ModuleName"].ToString();
var rows = from row in ds.Tables[0].AsEnumerable()
where row.Field<string>("ModuleName").Trim() == RootNode
select row;
DataTable dt = new DataTable();
dt = rows.CopyToDataTable();
if (dt != null)
{
if (dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
string GUID1 = Guid.NewGuid().ToString();
TreeNode MyChild = new TreeNode();
if ((dt.Rows[j]["PageName"].ToString().Trim() != "Master Config") && (dt.Rows[j]["PageName"].ToString().Trim() != "Upload") && (dt.Rows[j]["PageName"].ToString().Trim() != "label configuration") && (dt.Rows[j]["PageName"].ToString().Trim() != "Dashboard Report"))
{
MyChild.Text = " " + dt.Rows[j]["PageName"].ToString() + " " + "<input type='text' id='" + GUID1 + "' value='" + dt.Rows[j]["PageName"].ToString() + "'/>";
MyChild.Value = dt.Rows[j]["Address"].ToString();
MyRoot.ChildNodes.Add(MyChild);
}
}
}
}
}
}
The above code is working properly, but when I run the application and enter value in dynamic created text box then I am not getting this text box value for saving at run time. How we can access this value at run time?

Related

how to hide a column from google visualization

I have used below code to show google chart, I want to show another graph when clicking on first graph and here need to pass the value ResourceId
if (resourceDetails != null)
{
dataTable.Columns.Add("ResourceName", typeof(string));
dataTable.Columns.Add("ResourceId", typeof(int));
dataTable.Columns.Add("Planned", typeof(float));
dataTable.Columns.Add("Actual", typeof(float));
foreach (var item in resourceDetails.Distinct().ToArray())
{
dt = GetIndividualData(item.ResourceId, projectId);
if (dt.Rows.Count > 0)
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
DataRow row = dataTable.NewRow();
row["ResourceName"] = item.ResourceName;
row["ResourceId"] = item.ResourceId;
row["Planned"] = float.Parse(dt.Rows[i]["Planned"].ToString());
row["Actual"] = float.Parse(dt.Rows[i]["Actual"].ToString());
dataTable.Rows.Add(row);
}
}
}
if (dataTable.Rows.Count > 0)
{
stringBuilder.Append(#"<script type=*text/javascript*> google.load( *visualization*, *1*, {packages:[*corechart*]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'ResourceName');
data.addColumn('number', 'ResourceId');
data.addColumn('number', 'Planned');
data.addColumn({type: 'string', role: 'style'});
data.addColumn('number', 'Actual');
data.addColumn({type: 'string', role: 'style'});
");
// data.addRows(" + dataTable.Rows.Count + ");
for (int i = 0; i <= dataTable.Rows.Count - 1; i++)
{
if (Convert.ToDecimal(dataTable.Rows[i]["Planned"]) > Convert.ToDecimal(dataTable.Rows[i]["Actual"]))
{
stringBuilder.Append("data.addRow(['" + dataTable.Rows[i]["ResourceName"].ToString() + "'," + dataTable.Rows[i]["ResourceId"].ToString() + ", " + dataTable.Rows[i]["Planned"].ToString() + ",\'color:DeepSkyBlue\'," + dataTable.Rows[i]["Actual"].ToString() + ",\'color:green\']);");
}
else
{
stringBuilder.Append("data.addRow(['" + dataTable.Rows[i]["ResourceName"].ToString() + "', " + dataTable.Rows[i]["ResourceId"].ToString() + "," + dataTable.Rows[i]["Planned"].ToString() + ",\'color:DeepSkyBlue\'," + dataTable.Rows[i]["Actual"].ToString() + ",\'color:red\']);");
}
}
stringBuilder.Append(" var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));");
stringBuilder.Append(" chart.draw(data, {width: 660, height: 500, title: 'Resource-Performance Graph',");
stringBuilder.Append("legend: {position: 'none'},");
stringBuilder.Append("hAxis: {title: 'Resource', titleTextStyle: {color: 'green'},slantedText:true},width:'645',colors: ['DeepSkyBlue','green'],");
stringBuilder.Append("vAxis:{title: 'Effort (Hr)',titleTextStyle: {color: 'green'}}");
stringBuilder.Append("});");
stringBuilder.Append(" google.visualization.events.addListener(chart, 'onmouseover', function() {$('#chart_div').css('cursor','pointer');});");
stringBuilder.Append(" google.visualization.events.addListener(chart, 'onmouseout', function() {$('#chart_div').css('cursor','default');});");
stringBuilder.Append("google.visualization.events.addListener(chart, 'select', function() {");
stringBuilder.Append("var selection = chart.getSelection();var row = selection[0].row;var col = selection[0].column;var rId = data.getValue(row, 1); var pid = '" + projectId + "'; var pname = '" + projectName + "'; var resId = '" + Convert.ToInt32((Session["ResourceId"])) + "';");
stringBuilder.Append("location.href = '" + ConfigurationManager.AppSettings["SiteLink"].ToString() + "/IndividualGraph.aspx?pId=' + pid + '&pName=' + pname +'&pResId=' + rId ; ");
stringBuilder.Append("});");
stringBuilder.Append("}");
stringBuilder.Append("</script>");
lt.Text = stringBuilder.ToString().Replace('*', '"');
}
}
here I have used ResouceId column to pass the value as a parameter, but it shows in chart as a column, how can I hide this column from showing?
You can use the DataView Class to hide columns
var data = new google.visualization.DataTable();
data.addColumn('string', 'ResourceName');
data.addColumn('number', 'ResourceId');
data.addColumn('number', 'Planned');
data.addColumn({type: 'string', role: 'style'});
data.addColumn('number', 'Actual');
data.addColumn({type: 'string', role: 'style'});
var view = new google.visualization.DataView(data);
view.hideColumns([1]); // array of column indexes to hide
However, it may make sense in this case to use a Row Property instead
which does not appear in the chart
You can define your own properties with
setRowProperty(rowIndex, name, value)
and
getRowProperty(rowIndex, name)
The DataTable Class also has methods for Column and Cell Properties

Add lines below rows dynamically

I have written this code to send an email when an change is made in a gridview.
I send an email with changes made in the column in row format. I need to add a line below each row and I am using this code and it doesn't work.
I have used this part to add line below rows sbMsg.AppendFormat("<table rules=" + rows + " style=' font-family:Calibri;background-color:#F1F1F1' width='1000'>");
public string mailFormatting(string Code)
{
List<string> lstSpecificColumns = new List<string>();
DataTable dtCurrentTbl = activeApplication.LoadMailActiveApplications(Code.ToString().Trim());
DataTable dtOldTbl = activeApplication.LoadMailLogManualUpdatesDetails(Code.ToString().Trim());
for (int colIndex = 0; colIndex < dtCurrentTbl.Columns.Count; colIndex++)
{
if (!dtCurrentTbl.Rows[0][colIndex].ToString().Equals(dtOldTbl.Rows[0][colIndex].ToString()))
{
lstSpecificColumns.Add(dtCurrentTbl.Columns[colIndex].ColumnName);
}
}
dtCurrentTbl.Merge(dtOldTbl);
DataTable resultTbl = dtCurrentTbl.AsEnumerable().CopyToDataTable().DefaultView.ToTable(true, lstSpecificColumns.ToArray());
string rows = "\"rows\"";
StringBuilder sbMsg = new StringBuilder();
sbMsg.AppendFormat("<p><font color=gray>Title<font></p>");
sbMsg.AppendFormat("<table rules= + rows + style='font-family:Calibri;background-color:#F1F1F1' width='1000'>");
sbMsg.AppendFormat("<tr> <td colspan='2'> <font color=blue> <u> " + Code.ToString().Trim() + " </u></font><td></tr>");
foreach (DataColumn dc in resultTbl.Columns)
{
sbMsg.AppendFormat("<tr>");
sbMsg.AppendFormat("<td> " + dc.ColumnName.Trim() + " </td>");
sbMsg.AppendFormat("<td> <strike>" + resultTbl.Rows[1][dc].ToString().Trim() + "</strike>" + " " + resultTbl.Rows[0][dc].ToString().Trim() + " </td>");
sbMsg.AppendFormat("</tr>");
}
sbMsg.AppendFormat("</table>");
return sbMsg.ToString();
}
Can anyone help me in this.

fetch data from two different tables on same textbox changed event

I want to fetch some data from two different tables PRO and OPN_STK , in some controls like textboxs and datagridview . when i am selecting data from one table i.e. PRO ,the code is working perfect but when i applied same code just next to it , in same event for fetching data from another table i.e. OPN_STK it throws exception "object refrence not set to an instance of object" . I tried to know about the problem but now I'm blank , this is what I did ,
private void comboProname_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
//if (get == false) //in case when i need to apply condition which I dont prefer
{
string _sql = "select DISTINCT P_batchno,P_sh from PRO where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
//else if (get == true) // opnstk
{
string _sql = "select DISTINCT P_batchno,P_sh from OPN_STK where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
getdata();
}
private void comboBthNo_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
// if (get == false)
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from PRO where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
// else if (get == true) ///// opn stk ///////
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from OPN_STK where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows) // I get exception here only on dt
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
getdata();
}
i would appriciate any help ,thanks in advance .
Put a breakpoint in your code, debug and check that OPN_STK is not null. If it is null that would be your problem.

Filtering DataView with multiple columns

In my application I am using a dataview for having the filters to be applied where the filter options are passed dynamically.if there are 2 filter parameters then the dataview should be filtered for parameter1 and then by parameter two. I am using a method which is called in a for loop where I am setting the count to the total no.of parameters selected using a listbox but the filtering is done only for the last parameter.
Here is my code:
string str = "";
for (int i = 0; i < listbox.Items.Count; i++)
{
if (listbox.Items[i].Selected)
{
if (str != string.Empty)
{
str = str + "," + listbox.Items[i].Text;
}
else
{
str = str + listbox.Items[i].Text;
}
}
}
string[] items = str.Split(',');
for (int i = 0; i < items.Length; i++)
{
ApplyFilter(items[i],dv);
}
private DataView ApplyFilter(string str,DataView newdv)
{
newdv.RowFilter = "[" + str + "]=" + ddl.SelectedItem.ToString();
return newdv;
}
Please provide a suitable solution .
Thanks in advance...
You should apply your filter altogether, not one by one :
newdv.RowFilter = "Column1 = " + value1 + " AND Column2 = " + value2;
So you can change your code as :
string[] items = str.Split(',');
string filter = string.Empty;
for (int i = 0; i < items.Length; i++)
{
filter += items[i] + " = " + dropdown.SelectedValue;
if (i != items.Length - 1)
{
filter += " AND ";
}
}
newdv.RowFilter = filter;
I think you should build a complete filter string and then set this filter to your DataView.
For example:
StringBuilder sb = new StringBuilder()
for (int i = 0; i < listbox.Items.Count; i++) {
if (!listbox.Items[i].Selected) {
continue;
}
if (sb.Length > 0) {
sb.Append(" and ");
}
sb.AppendFormat("[{0}] = {1}", listbox.Items[i].Text, ddl.SelectedItem);
}
dv.RowFilter = sb.ToString();
DataView dv = new DataView(dt);
string filterText = "some search criteria";
dv.RowFilter = "Column1 + Column2 + Column3 Like '%" + filterText + "%'";
I had a similar problem - but i think solution will be the same for both of them. I have a datatable that needs to be filtered by 5 controls and if they aren't filled - it shouldn't be filtered.
List<string> allParams = new List<string>();
//here add fields you want to filter and their impact on rowview in string form
if (tsPrzelewyTxtOpis.Text != ""){ allParams.Add("Opis like '%" + tsPrzelewyTxtOpis.Text + "%'"); }
if(tsPrzelewyTxtPlatnik.Text != ""){ allParams.Add("Płacący like '%" + tsPrzelewyTxtPlatnik.Text + "%'"); }
if(tsPrzelewyDropDownKonto.Text != "") { allParams.Add("Konto = '" + tsPrzelewyDropDownKonto.Text + "'"); }
if (tsPrzelewyDropDownWaluta.Text != "") { allParams.Add("Waluta = '" + tsPrzelewyDropDownWaluta.Text + "'"); }
if (tsPrzelewyDropDownStatus.Text != "") { allParams.Add("Status = '" + tsPrzelewyDropDownStatus.Text + "'"); }
string finalFilter = string.Join(" and ", allParams);
if (finalFilter != "")
{ (dgvPrzelewy.DataSource as DataTable).DefaultView.RowFilter = "(" + finalFilter + ")"; }
else
{ (dgvPrzelewy.DataSource as DataTable).DefaultView.RowFilter = ""; }

Sending changes from multiple tables in disconnected dataset to SQLServer

We have a third party application that accept calls using an XML RPC mechanism for calling stored procs.
We send a ZIP-compressed dataset containing multiple tables with a bunch of update/delete/insert using this mechanism. On the other end, a CLR sproc decompress the data and gets the dataset.
Then, the following code gets executed:
using (var conn = new SqlConnection("context connection=true"))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
try
{
foreach (DataTable table in ds.Tables)
{
string columnList = "";
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 0)
columnList = table.Columns[0].ColumnName;
else
columnList += "," + table.Columns[i].ColumnName;
}
var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn);
var builder = new SqlCommandBuilder(da);
builder.ConflictOption = ConflictOption.OverwriteChanges;
da.RowUpdating += onUpdatingRow;
da.Update(ds, table.TableName);
}
}
catch (....)
{
.....
}
}
Here's the event handler for the RowUpdating event:
public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e)
{
if ((e.StatementType == StatementType.Update) && (e.Command == null))
{
e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter);
e.Status = UpdateStatus.Continue;
}
}
and the CreateUpdateCommand method:
private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da)
{
string whereClause = "";
string setClause = "";
SqlConnection conn = da.SelectCommand.Connection;
for (int i = 0; i < row.Table.Columns.Count; i++)
{
char quoted;
if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) ||
(row.Table.Columns[i].DataType == Type.GetType("System.DateTime")))
quoted = '\'';
else
quoted = ' ';
string val = row[i].ToString();
if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean"))
val = (bool)row[i] ? "1" : "0";
bool isPrimaryKey = false;
for (int j = 0; j < row.Table.PrimaryKey.Length; j++)
{
if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName)
{
if (whereClause != "")
whereClause += " AND ";
if (row[i] == DBNull.Value)
whereClause += row.Table.Columns[i].ColumnName + "=NULL";
else
whereClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
isPrimaryKey = true;
break;
}
}
/* Only values for column that is not a primary key can be modified */
if (!isPrimaryKey)
{
if (setClause != "")
setClause += ", ";
if (row[i] == DBNull.Value)
setClause += row.Table.Columns[i].ColumnName + "=NULL";
else
setClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
}
}
return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn);
}
However, this is really slow when we have a lot of records.
Is there a way to optimize this or an entirely different way to send lots of udpate/delete on several tables? I would really much like to use TSQL for this but can't figure a way to send a dataset to a regular sproc.
Additional notes:
We cannot directly access the SQLServer database.
We tried without compression and it was slower.
If you're using SQL Server 2008, you should look into MERGE
Look here for more info on MERGE

Categories