How to update different view separately in a multiview control - c#

I created a multiview control with different views. Each views have separate edit buttons which should update the fields only in that view. The edit button is working properly on the first view/tab. But not in the others. I have used update panels in different tables in different views. Still not working. Blow is the code.
Found out hat the code is not able to find any control inside the table content. But why?
<asp:Button Text="Information" BorderStyle="None" ID="Tab1" CssClass="Initial" runat="server" OnClick="Tab1_Click" />
<asp:Button Text="IP Adresses" BorderStyle="None" ID="Tab2" CssClass="Initial" runat="server" OnClick="Tab2_Click" />
<asp:MultiView ID="MainView" runat="server">
<asp:View ID="View1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="div1" runat="server" >
<table id="tableContentInfo" style="width: 80%;" runat="server"></table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:View>
<asp:View ID="View2" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="div2" runat="server" >
<table id="tableContentMake_Model" style="width: 100%;" runat="server"></table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:View>
</asp:MultiView>
This is the code behind.. the controls inside the views are created dynamically and they are showing properly with data. tableContentMake_Model is the second view id.
string strServer = "";
protected void Page_Init(object sender, EventArgs e)
{
GetDataFromSession();
lblName.Text = strServer;
LoadViewInfo(strServer);
LoadViewMake_Model(strServer);
}
protected void Page_Load(object sender, EventArgs e)
{
Tab1.CssClass = "Clicked";
Tab2.CssClass = "Initial";
Tab3.CssClass = "Initial";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 0;
}
protected void Tab1_Click(object sender, EventArgs e)
{
Tab1.CssClass = "Clicked";
Tab2.CssClass = "Initial";
Tab3.CssClass = "Initial";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 0;
GetDataFromSession();
LoadViewInfo(strServer);
}
protected void Tab2_Click(object sender, EventArgs e)
{
Tab1.CssClass = "Initial";
Tab2.CssClass = "Clicked";
Tab3.CssClass = "Initial";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 1;
GetDataFromSession();
LoadViewMake_Model(strServer);
}
private void button_Edit_MakeModel_Click(object sender, EventArgs e)
{
foreach (HtmlTableRow row in tableContentMake_Model.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control ctrl in cell.Controls)
{
if (ctrl.GetType() != typeof(LiteralControl))
{
if (ctrl is HtmlInputCheckBox)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox)ctrl;
chk.Disabled = false;
}
if (ctrl is HtmlInputText)
{
HtmlInputText txt = (HtmlInputText)ctrl;
txt.Attributes.Remove("readonly");
txt.Style.Add("border", "1px solid #DBE0E4");
}
if (ctrl is HtmlTextArea)
{
HtmlTextArea txtarea = (HtmlTextArea)ctrl;
txtarea.Attributes.Remove("readonly");
txtarea.Style.Add("border", "1px solid #DBE0E4");
}
}
}
}
}
Button btnEdit = (Button)tableContentMake_Model.FindControl("Edit_MakeModel");
btnEdit.Visible = false;
Button btnSave = (Button)tableContentMake_Model.FindControl("Save_MakeModel");
btnSave.Visible = true;
Button btnCancel = (Button)tableContentMake_Model.FindControl("Cancel_MakeModel");
btnCancel.Visible = true;
}
Thanks in advance for help.
This is the creation of button code..
int ct = 0;
int nullct = 0;
string fields = "";
string strControl = "";
tableContentMake_Model.Rows.Clear();
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["WebTeamServersConnectionString"].ConnectionString);
string sCommand = "select * from server_List_Choices where ListHeading='Make_Model'";
SqlCommand command = new SqlCommand(sCommand, cn);
cn.Open();
SqlDataReader reader = command.ExecuteReader();
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
while (reader.Read())
{
if (ct == 0)
{
cell.InnerText = reader.GetValue(3).ToString().Trim();
cell.Width = "50px";
cell.Style.Add("font-weight", "bold");
cell.Style.Add("color", "#69be28");
row.Cells.Add(cell);
fields = reader.GetValue(2).ToString().Trim();
strControl = reader.GetValue(4).ToString().Trim();
}
else
{
cell = new HtmlTableCell();
cell.InnerText = reader.GetValue(3).ToString().Trim();
if (reader.GetValue(3).ToString().Trim() == "Operating System")
{
cell.Width = "150px";
}
else
{
cell.Width = "40px";
}
cell.Style.Add("font-weight", "bold");
cell.Style.Add("color", "#69be28");
row.Cells.Add(cell);
fields = fields + "," + reader.GetValue(2).ToString().Trim();
strControl = strControl + "," + reader.GetValue(4).ToString().Trim();
}
ct = ct + 1;
}
tableContentMake_Model.Rows.Add(row);
cn.Close();
SqlConnection cn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["WebTeamServersConnectionString"].ConnectionString);
string sCommand1 = "select " + fields + " from [Web Team Servers] where Server='" + server + "'";
SqlCommand command1 = new SqlCommand(sCommand1, cn1);
cn1.Open();
SqlDataReader reader1 = command1.ExecuteReader();
row = new HtmlTableRow();
while (reader1.Read())
{
for (int i = 0; i < reader1.VisibleFieldCount; i++)
{
cell = new HtmlTableCell();
if ((reader1.GetValue(i).ToString().Trim() == "") || (reader1.GetValue(i).ToString().Trim() == null))
{
nullct = nullct + 1;
}
string[] s = strControl.Split(',');
string p = s[i];
switch (p)
{
case "chk":
HtmlInputCheckBox checkbox = new HtmlInputCheckBox();
if (reader1.GetValue(i).ToString().Trim() == "Y")
{
checkbox.Checked = true;
}
else
{
checkbox.Checked = false;
}
checkbox.Disabled = true;
cell.Controls.Add(checkbox);
row.Cells.Add(cell);
break;
case "txt":
string valuetxt = reader1.GetValue(i).ToString().Trim();
HtmlInputText textbox = new HtmlInputText();
textbox.Value = valuetxt;
textbox.ID = "txt" + reader1.GetName(i).ToString().Trim();
textbox.Attributes.Add("readonly", "readonly");
textbox.Style.Add("border", "none");
if (reader1.GetName(i).ToString().Trim() == "OperatingSystem")
{
textbox.Style.Add("width", "300px");
}
else
{
textbox.Style.Add("width", "100px");
}
cell.Controls.Add(textbox);
break;
case "txtarea":
string value = reader1.GetValue(i).ToString().Trim();
value = value.Replace("\"", "");
value = value.Replace("\n", "");
value = value.Replace("\r", "");
value = value.Replace("~", "\n");
HtmlTextArea testarea = new HtmlTextArea();
testarea.Value = value;
testarea.ID = "txtarea" + reader1.GetName(i).ToString().Trim();
testarea.Attributes.Add("readonly", "readonly");
testarea.Style.Add("border", "none");
testarea.Style.Add("height", "50px");
cell.Controls.Add(testarea);
cell.Width = "30px";
break;
default :
break;
}
cell.Style.Add("color", "black");
row.Cells.Add(cell);
}
if (nullct < reader1.VisibleFieldCount)
{
cell = new HtmlTableCell();
Button button = new Button();
button.Text = "Edit";
button.ID = "Edit_MakeModel";
button.Click += new EventHandler(button_Edit_MakeModel_Click);
cell.Controls.Add(button);
cell.Width = "50px";
row.Cells.Add(cell);
cell = new HtmlTableCell();
Button button1 = new Button();
button1.Text = "Save";
button1.ID = "Save_MakeModel";
button1.Visible = false;
button1.Click += new EventHandler(button_Save_MakeModel_Click);
cell.Controls.Add(button1);
cell.Width = "50px";
row.Cells.Add(cell);
cell = new HtmlTableCell();
Button button2 = new Button();
button2.Text = "Cancel";
button2.ID = "Cancel_MakeModel";
button2.Visible = false;
button2.Click += new EventHandler(button_Cancel_MakeModel_Click);
cell.Controls.Add(button2);
cell.Width = "50px";
row.Cells.Add(cell);
}
tableContentMake_Model.Rows.Add(row);
}
cn1.Close();

I think you can have one Update panel for all the views in common that is above the multi view control.I usally use in that way.Hope that can give the hint to your problem.
Please let me know if your problem solved.
Thanks

Solved the issue...
protected void Page_Load(object sender, EventArgs e)
{
switch (strClicked)
{
case "Tab1" :
Tab1.CssClass = "Clicked";
Tab2.CssClass = "Initial";
Tab3.CssClass = "Initial";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 0;
break;
case "Tab2" :
Tab1.CssClass = "Initial";
Tab2.CssClass = "Clicked";
Tab3.CssClass = "Initial";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 1;
break;
case "Tab3" :
Tab1.CssClass = "Initial";
Tab2.CssClass = "Initial";
Tab3.CssClass = "Clicked";
Tab4.CssClass = "Initial";
Tab5.CssClass = "Initial";
Tab6.CssClass = "Initial";
MainView.ActiveViewIndex = 2;
break;
default :
break;
}
}

Related

How to assign methods to a dynamic created Gridview?

I have the following class which is the class for creating a gridview dynamic:
public class DynamicGridViewImageButtonTemplate : ITemplate
{
string _ColName;
DataControlRowType _rowType;
int _Count;
int _Kind;
public DynamicGridViewImageButtonTemplate(string ColName, DataControlRowType RowType, int Kind)
{
_ColName = ColName;
_rowType = RowType;
_Kind = Kind;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.DataRow:
if (_Kind == 0)
{
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.lbl_DataBind);
container.Controls.Add(lbl);
}
else
if (_Kind == 1)
{
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
container.Controls.Add(vImageButton);
}
break;
default:
break;
}
}
and the following c# code for assigning methods runtime to the imagebutton which I have created in a column:
protected void btnGetVoucher_Command(object sender, CommandEventArgs e)
{
ImageButton btn = sender as ImageButton;
}
protected void gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
}
}
and the creating of the gridcolumn is as follows:
GridView vGridView = new GridView();
vGridView.RowCreated += new GridViewRowEventHandler(gridview_RowCreated);
vTemplateField = new TemplateField();
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header, 0);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow, 1);
vGridView.Columns.Add(vTemplateField);
And at last the databind here:
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, "Voucher").ToString();
}
But I can't step into the method btnGetVoucher_Command :-( I think that everything has been made correctly - but there must be something I have missed somewhere...
I can access the button in my Row_Created routine - but afterwards not use the GetVoucherCommand :-( the event is not fired :-(
So my question is why can't I step into that routine?
Thanks in advance,
Michael
Update:
The full class is here...
public class DynamicGridViewTextTemplate : ITemplate
{
string _ColNameText;
DataControlRowType _rowType;
public DynamicGridViewTextTemplate(string ColNameText, DataControlRowType RowType)
{
_ColNameText = ColNameText;
_rowType = RowType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = "<b>" + _ColNameText + "</b>";
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.ImageUrl = "~/Images/Icons/icons8-download-from-the-cloud-50.png";
vImageButton.PostBackUrl = "#DownloadVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.ToolTip = "Se og download bilag";
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
vImageButton.CommandName = "DownloadVoucher";
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
container.Controls.Add(vImageButton);
break;
default:
break;
}
}
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, _ColNameText).ToString();
}
}
public class DynamicGridViewImageButtonTemplate : ITemplate
{
string _ColNameText;
DataControlRowType _rowType;
public DynamicGridViewImageButtonTemplate(string ColNameText, DataControlRowType RowType)
{
_ColNameText = ColNameText;
_rowType = RowType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_rowType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = "<b>" + _ColNameText + "</b>";
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
ImageButton vImageButton = new ImageButton();
vImageButton.ID = "btnGetVoucher";
vImageButton.ImageUrl = "~/Images/Icons/icons8-download-from-the-cloud-50.png";
vImageButton.PostBackUrl = "#DownloadVoucher";
vImageButton.CommandArgument = string.Format("<%# Eval({0}) %>", "Voucher");
vImageButton.ToolTip = "Se og download bilag";
vImageButton.CssClass = "divButton";
vImageButton.Height = 25;
vImageButton.Width = 25;
vImageButton.DataBinding += new EventHandler(this.imgBtn_DataBind);
vImageButton.CommandName = "DownloadVoucher";
vImageButton.Command += new CommandEventHandler(btnGetVoucher_Command);
container.Controls.Add(vImageButton);
break;
default:
break;
}
}
protected void btnGetVoucher_Command(object sender, CommandEventArgs e)
{
ImageButton btn = sender as ImageButton;
}
private void imgBtn_DataBind(Object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
btn.CommandArgument = DataBinder.Eval(row.DataItem, _ColNameText).ToString();
}
}
The events is here...
protected void gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
}
}
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton vImageButton = (ImageButton)e.Row.FindControl("btnGetVoucher");
}
}
protected void gridview_RowCommand(object sender, CommandEventArgs e)
{
if (e.CommandName == "DownloadVoucher")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView grid = sender as GridView;
GridViewRow row = grid.Rows[index];
ImageButton vImageButton = (ImageButton)row.FindControl("btnGetVoucher");
}
}
The creating of the gridview is here...
GridView vGridView = new GridView();
vGridView.AutoGenerateColumns = false;
vGridView.ShowHeaderWhenEmpty = true;
vGridView.ShowHeader = true;
vGridView.HeaderStyle.BackColor = System.Drawing.ColorTranslator.FromHtml("#C6E0B4");
vGridView.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
vGridView.RowCreated += new GridViewRowEventHandler(gridview_RowCreated);
vGridView.RowDataBound += new GridViewRowEventHandler(gridview_RowDataBound);
vGridView.RowCommand += new GridViewCommandEventHandler(gridview_RowCommand);
vTemplateField = new TemplateField();
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow);
vGridView.Columns.Add(vTemplateField);
micheal.
in this code, i can't see event handling code in InstantiateIn method.
ex) like this.
lbl.DataBinding += new EventHandler(this.btnGetVoucher_Command);
DynamicGridViewTextTemplate class constructor args are 3 count.
but, when using DynamicGridViewTextTemplate constructor,
used only 2 count args.
where is kind?
try it.
vTemplateField.HeaderTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.Header, 0);
vTemplateField.ItemTemplate = new DynamicGridViewImageButtonTemplate("Voucher", DataControlRowType.DataRow, 1);
best example in msdn
https://learn.microsoft.com/ko-kr/dotnet/api/system.web.ui.webcontrols.templatefield.-ctor?view=netframework-4.8
I hope this answer helps you.

Creating Row Dynamically based on selecting dropdownlist

I written a code for creating dynamically table. the table containing textbox and Dropdownlist.
i try to do creating table based on selected dropdowlist value when i select dropdown list like "Splitter1:5" than Table row will creating 5 . first time it has done successfully when i try to second time i did not get the value of dropdown list.
i am sharing my code please help me.
html code:
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlTextBoxes" runat="server">
<asp:ListItem Value="2" Text="Splitter1:2" />
<asp:ListItem Value="4" Text="Splitter1:4" />
<asp:ListItem Value="8" Text="Splitter1:8" />
<asp:ListItem Value="1" Text="Joint" />
<asp:ListItem Value="0" Text="OLT" />
</asp:DropDownList>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" /><br />
<asp:Panel ID="container" runat="server" Visible="false"> <asp:Button ID="btnSubmit" runat="server" Text="Process" OnClick="Submit" /></asp:Panel>
</div>
</form>
</body>
behind code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class testform : System.Web.UI.Page
{
DropDownList DDL; int i;
ArrayList arry_value = new ArrayList(); object[] obj;
Panel pn;
protected void Page_Load(object sender, EventArgs e)
{
//ViewState["droplist"] = obj;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value);
// DataTable dt = new DataTable();
//dt.Columns.Add("First Textbox");
// dt.Columns.Add("Dropdownlist");
// dt.Columns.Add("Last Textbox");
var table = new Table();
for (i = 0; i < numOfTxt; i++)
{
var row = new TableRow();
var cell = new TableCell();
// var thr = new TableHeaderRow();
// var heading = new TableHeaderCell();
//TableHeaderCell thPNumber = new TableHeaderCell();
// cell.Attributes.Add("runat", "server");
TextBox textbox = new TextBox();
textbox.ID = "Textbox" + i;
textbox.Text = "text" + i;
textbox.Width = new Unit(180);
TextBox textbox1 = new TextBox();
textbox1.ID = "Textbox1" + i;
textbox1.Text = "text1" + i;
textbox1.Width = new Unit(180);
DDL = new DropDownList();
DDL.ID = "DDL1" + i;
DDL.Items.Add("Select Splitter");
DDL.Items.Add(new ListItem("Splitter1:2", "2"));
DDL.Items.Add(new ListItem("Splitter1:4", "4"));
DDL.Items.Add(new ListItem("Splitter1:8", "8"));
DDL.Items.Add(new ListItem("Joint", "1"));
DDL.Items.Add(new ListItem("ONT", "0"));
DDL.AutoPostBack = true;
DDL.TextChanged += dropDown_TextChanged;
// dt.Rows.Add(textbox1);
cell.Controls.Add(textbox1);
cell.Controls.Add(DDL);
cell.Controls.Add(textbox);
//dt.Rows.Add(DDL);
//string val = DDL.SelectedItem.Value;
// string val = DDL.SelectedValue;
// dt.Rows.Add(textbox);
row.Cells.Add(cell);
// row.Cells.Add(thr);
table.Rows.Add(row);
arry_value.Add(DDL.ID);
foreach (object obj in arry_value)
{
var idcollection = new string[] { obj.ToString() };
}
//for (int i1 = 0; i1 < arry_value.Count; i1++)
//{
// //var empty1 = new string[] {arry_value[i].ToString() };
// obj = new object[] { arry_value[i]};
//}
//string count += (DDL.ID.SelectedItem.Value).toString();
}
pn = new Panel();
pn.ID = "pan" + i + 1;
this.form1.Controls.Add(pn);
container.Visible = true;
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Processone";
btnSubmit.Click += new System.EventHandler(Submit);
container.Controls.Add(table);
//pn.Controls.Add(btnSubmit);
// container.Controls.AddAt(0, table);
}
void dropDown_TextChanged(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
}
protected void Submit(object sender, EventArgs e)
{
//Student stud = (Student)ViewState["CurrentStudent"];
//DropDownList ddl = (DropDownList)container.FindControl("DDL1"+i);
// int numOfTxt = 4;
int numOfTxt = 5;
string drpvalue;
for (int j = 0; j < Convert.ToInt32(ddlTextBoxes.SelectedItem.Value); j++)
{
drpvalue = "DDL12" + i + ".SelectedItem.Value";
//int te = Convert.ToInt32(drpvalue);
// numOfTxt += Convert.ToInt32(DDL120.SelectedItem.Value);
}
//int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value);
var table = new Table();
DataTable dt = new DataTable();
for (int i = 0; i < numOfTxt; i++)
{
var row = new TableRow();
var cell = new TableCell();
// dt.Columns.Add("TextOne1");
cell.Attributes.Add("runat", "server");
TextBox textbox = new TextBox();
textbox.ID = "Textbox" + i;
textbox.Text = "text" + i;
textbox.Width = new Unit(180);
TextBox textbox1 = new TextBox();
textbox1.ID = "Textbox1" + i;
textbox1.Text = textbox1.Text;
textbox1.Width = new Unit(180);
DropDownList DDLs = new DropDownList();
DDLs.ID = "DDL12" + i;
// count= Convert.ToInt32( DDL.ID = "DDL12" + i);
DDLs.Items.Add("Select Splitter");
DDLs.Items.Add(new ListItem("Splitter1:2", "2"));
DDLs.Items.Add(new ListItem("Splitter1:4", "4"));
DDLs.Items.Add(new ListItem("Splitter1:8", "8"));
DDLs.Items.Add(new ListItem("Joint", "1"));
DDLs.Items.Add(new ListItem("ONT", "0"));
//DDLs.AutoPostBack = true;
DDLs.TextChanged += dropDown_TextChanged;
// dt.Rows.Add(textbox1);
cell.Controls.Add(textbox1);
// dt.Columns.Add("ListDropdown");
cell.Controls.Add(DDLs);
// dt.Columns.Add("Textbodx");
cell.Controls.Add(textbox);
row.Cells.Add(cell);
table.Rows.Add(row);
}
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Process";
btnSubmit.Click += new System.EventHandler(Submit);
Panel pans = new Panel();
pans.ID = "panss";
this.form1.Controls.Add(pans);
pans.Controls.AddAt(0, table);
pans.Controls.Add(btnSubmit);
pans.Visible = true;
//pn.Visible = true;
}
}

Prevent to add a column twice to the datagridview

I have a MetroFramework.Controls.MetroGrid in my windows forms application. In frmPatientList_Shown I call a method loadPatientList(). I also add a DataGridViewLinkColumn after binding the dtb to the gridview.
Clicking the link opens a new form where I update Patient data, and on formEditPatient.FormClosed I call the loadPatientList() method again, This time the DataGridViewLinkColumn is being added twice. How can I prevent to Add the link twice ?
Here is my code:
private void frmPatientList_Shown(object sender, EventArgs e)
{
loadPatientList();
}
private void loadPatientList()
{
DataTable dtb = Patient.getPatientList();
bindToGrid(dtb);
}
private void bindToGrid(DataTable dtb)
{
dataGridView1.DataSource = null;
using (dtb)
{
dataGridView1.DataSource = dtb;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns[0].Name = "PatientId";
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[0].DataPropertyName = "PatientId";
// more code here.
}
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = " Edit ";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 8 && e.RowIndex >= 0)
{
using (frmEditPatient formEditPatient = new frmEditPatient(id))
{
formEditPatient.FormClosed += FormEditPatient_FormClosed;
formEditPatient.ShowDialog();
}
}
}
private void FormEditPatient_FormClosed(object sender, FormClosedEventArgs e)
{
loadPatientList();
}
Any help would be appreciated.
You check if the column exist,
bool hasEditColumn = false;
foreach (DataGridViewColumn item in dataGridView1.Columns)
{
if (item.GetType() == typeof(DataGridViewLinkColumn) && item.HeaderText == "Edit")
{
hasEditColumn = true;
break;
}
}
if (!hasEditColumn)
{
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = "Edit";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
dataGridView1.Refresh();
}
In frmPatientList_Shown function you add the link
private void frmPatientList_Shown(object sender, EventArgs e)
{
DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
EditLink.UseColumnTextForLinkValue = true;
EditLink.HeaderText = " Edit ";
EditLink.DataPropertyName = "lnkColumn";
EditLink.LinkBehavior = LinkBehavior.SystemDefault;
EditLink.Text = "Edit";
dataGridView1.Columns.Add(EditLink);
loadPatientList();
}
In bindToGrid function you do not add the link
private void bindToGrid(DataTable dtb)
{
dataGridView1.DataSource = null;
using (dtb)
{
dataGridView1.DataSource = dtb;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns[0].Name = "PatientId";
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[0].DataPropertyName = "PatientId";
// more code here.
}
//DataGridViewLinkColumn EditLink = new DataGridViewLinkColumn();
//EditLink.UseColumnTextForLinkValue = true;
//EditLink.HeaderText = " Edit ";
//EditLink.DataPropertyName = "lnkColumn";
//EditLink.LinkBehavior = LinkBehavior.SystemDefault;
//EditLink.Text = "Edit";
//dataGridView1.Columns.Add(EditLink);
}
I hope it will help you.

Event on dynamically created checkbox asp.net

I started to programming with asp.net, I have a table with some checkboxes.
The problem is, I can't create static tables, because this action is linked with some parameters. Anyway.. When I click on the First checkbox I want to invert the other checkboxes in this table.
How can I catch this event?
<%# Page Title="Fragebogen generieren" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Generate.aspx.cs" Inherits="MAXXREC.Generate" SmartNavigation="True" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2><br /> <br />
<asp:Panel id="pCustomize" runat="server"></asp:Panel> <br /><br />
<asp:Button id="btnSave" class="btn btn-default" Text="Save" runat="server" OnClick="btnSave_Click"></asp:Button>
</asp:Content>
private bool SelectTheData()
{
dtQuestionBlock = taQuestionBlock.GetData();
try
{
int rows = dtQuestionBlock.Rows.Count;
for (int i = 0; i < rows; i++)
{
UpdatePanel updatePanel = new UpdatePanel();
updatePanel.ID = "up" + dtQuestionBlock.Rows[i][1].ToString();
Label lbl = new Label();
lbl.ID = "lbl" + dtQuestionBlock.Rows[i][1].ToString();
lbl.CssClass = "h4";
lbl.Attributes.Add("runat", "server");
lbl.Text = dtQuestionBlock.Rows[i][1].ToString();
pCustomize.Controls.Add(lbl);
pCustomize.Controls.Add(new Literal() { ID = "br" + i, Text = "<br /><br />" });
HtmlTable tbl = new HtmlTable();
tbl.Width = "100%";
tbl.Attributes.Add("class", "table");
tbl.ID = "htmltbl" + dtQuestionBlock.Rows[i][1].ToString();
HtmlTableRow htr = new HtmlTableRow();
HtmlTableCell hcella = new HtmlTableCell();
CheckBox acb = new CheckBox();
acb.ID = "cb" + dtQuestionBlock.Rows[i]["name"].ToString();
//acb.CheckedChanged += new EventHandler(cb_CheckedChanged);
hcella.Width = "30px";
hcella.Controls.Add(acb);
htr.Cells.Add(hcella);
HtmlTableCell hcellf = new HtmlTableCell();
hcellf.InnerText = "Frage";
hcellf.Style.Add("font-weight", "bold");
hcellf.Style.Add("font-size", "15px");
htr.Cells.Add(hcellf);
tbl.Rows.Add(htr);
string cont = dtQuestionBlock.Rows[i]["ID"].ToString();
dtQuestion = taQuestion.GetDataBy1(Convert.ToInt32(cont));
nCountTables = i;
for (int j = 0; j < dtQuestion.Rows.Count; j++)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
acb = new CheckBox();
acb.ID = "cb" + dtQuestion.Rows[j]["content"].ToString();
cell.Width = "30px";
cell.Controls.Add(acb);
tr.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = dtQuestion.Rows[j]["content"].ToString();
cell.ID = "cell" + j + "_" + dtQuestion.Rows[j]["content"].ToString();
tr.Cells.Add(cell);
tbl.Rows.Add(tr);
}
updatePanel.ContentTemplateContainer.Controls.Add(tbl);
//tbl.Visible = false;
pCustomize.Controls.Add(updatePanel);
pCustomize.Controls.Add(new Literal() { ID = "br" + i + rows, Text = "<br />" });
}
return true;
}
catch (Exception ex)
{
Type cstype = ex.GetType();
ClientScriptManager cs = Page.ClientScript;
String cstext = ex.ToString();
cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
return false;
}
finally
{
taQuestionBlock.Dispose();
dtQuestionBlock.Dispose();
}
}
you can try this code
List<CheckBox> lstChckBox;
protected void Page_Load(object sender, EventArgs e)
{
// you can create controls programaticaly or html page, doesnt important
//only you should know controls ID and all controls share same checked event
CheckBox chc1 = new CheckBox();
chc1.CheckedChanged += new EventHandler(chck_CheckedChanged);
CheckBox chc2 = new CheckBox();
chc2.CheckedChanged += new EventHandler(chck_CheckedChanged);
CheckBox chc3 = new CheckBox();
chc3.CheckedChanged += new EventHandler(chck_CheckedChanged);
// Now, you can create a List so event is fired, you can catch which controls checked or not
lstChckBox = new List<CheckBox>();
lstChckBox.Add(chc1);
lstChckBox.Add(chc2);
lstChckBox.Add(chc3);
}
void chck_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (sender as CheckBox);
foreach (CheckBox item in lstChckBox)
{
if (item != checkBox)
{
item.CheckedChanged -= new EventHandler(chck_CheckedChanged);
item.Checked = !checkBox.Checked;
item.CheckedChanged += new EventHandler(chck_CheckedChanged);
}
}
}

Bind ListView to dynamic Accordion

In the page_load I'm creating dynamically the headers using data from SpGetCompanies, which is working fine. Then I'm trying to add a ListView to every dynamically created accordion pane with the data source SpSearchPublicationsTop1.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
SQLConnection dataAccessor = new SQLConnection();
dtCompanies = dataAccessor.SpGetCompanies();
if (dtCompanies.Rows.Count > 0)
{
AccordionPane pn;
Label lblContent;
int j = 0;
for (int i = 0; i < dtCompanies.Rows.Count; i++)
{
lblHeader = new Label();
lblHeader.Text = dtCompanies.Rows[i][1].ToString();
lblContent = new Label();
lblContent.Text = "Hallo";
pn = new AccordionPane();
pn.ID = "Pane" + j;
pn.HeaderContainer.Controls.Add(lblHeader);
ListView view = new ListView();
view.LayoutTemplate = new LayoutTemplate();
view.ItemTemplate = new ItemTemplate();
//view = (ListView)FindControl("lv_result");
view.DataSource = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
view.DataBind();
#region commented stuff
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// //view = (ListView)FindControl("lv_result");
// //column1.Text = dt2.Rows[0][0].ToString();
// //view.Columns.Add(column1);
// //Label lblAcronym = new Label();
// //lblAcronym.Text = dt2.Rows[0][0].ToString();
// //view.DataSource = lblAcronym;
// view.DataSource = dt2;
// view.DataBind();
//}
//listView1.Columns.Add(column1);
//foreach (DataRow dr in dt2.Rows)
//{
// ListViewItem lvi = new ListViewItem(dr[0].ToString()); //1.st column in datatable, instead of 0 you can write column`s name like: ["CustomerID"]
// lvi.SubItems.Add(dr[1].ToString()); //2nd column from datatable
// view.Items.Add(lvi);
//}
//this.Controls.Add(view);
//ListView lv_result = new ListView();
////lv_result.ItemTemplate = new ItemTemplate();
//lv_result.ID = "lvpane" + i;
//lv_result.Visible = true;
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// lv_result.DataSource = dt2;
// lv_result.DataBind();
//}
//var level2 = (ListView)FindControl("lv_result");
//level2.ItemTemplate = view.ItemTemplate;
////level2.DataSource = dt2(e.AccordionItem.DataItemIndex);
////level2.DataBind();
//dt2 = SQLConnection.SpSearchPublicationsTop1(lblHeader.Text);
//if (dt2.Rows.Count > 0)
//{
// level2.DataSource = dt2;
// level2.DataBind();
//}
#endregion
pn.ContentContainer.Controls.Add(view);
//pn.ContentContainer.Controls.Add(lblContent);
Accordion1.Panes.Add(pn);
++j;
}
}
}
}
private class LayoutTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var ol = new HtmlGenericControl("ol");
var li = new HtmlGenericControl("li") { ID = "itemPlaceholder" };
ol.Controls.Add(li);
container.Controls.Add(ol);
}
}
private class ItemTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
var li = new HtmlGenericControl("li");
li.DataBinding += DataBinding;
container.Controls.Add(li);
}
public void DataBinding(object sender, EventArgs e)
{
var container = (HtmlGenericControl)sender;
var dataItem = ((ListViewDataItem)container.NamingContainer).DataItem;
container.Controls.Add(new Literal() { Text = dataItem.ToString() });
}
}
With the code above the headers from the accordion are working fine, but instead of the ListView data in the content I'm only getting: System.Data.DataRowView
What am I doing wrong?
You are missing a call to:
DataBinder.Eval(container.DataItem, "YouBindingProperty");
Example:
public void DataBinding(object sender, EventArgs e)
{
var genericControl = (HtmlGenericControl)sender;
var container = (ListViewDataItem)container.NamingContainer;
container.Controls.Add(new Literal() { Text = DataBinder.Eval(container.DataItem, "YouBindingProperty") });
}

Categories