I have 2 buttons that is supposed to update the db, and when it updates the page should do a postback with the updated info, however...right now it updates in db alright, but the page doesnt update until the 2nd click, and then the clicks afterwards are alright until i clicked on anohter tab...everything happens all over again...btw the buttons are called up and down, they are dynamically created inside a template that creates the grid
so the up/down button is built right after page_load, the page_load function calls the loaddisplaygrid(or loaddynamicdisplaygrid), then in the loaddisplaygrid(or loaddynamicdisplaygrid) function it builds the template that build the buttons
//page load
protected void Page_Load(object sender, EventArgs e)
{
RadToolBarItem textbxItem = MainRadToolBar.Items.FindItemByText("textbox");
RadTextBox displayName = (RadTextBox)textbxItem.FindControl("displayName");
Session["UserID"] = getUserID();
if (!Page.IsPostBack)
{
if (Profile.ShowFilter)
{
displayMenuBar.Style["display"] = "block";
displayLineBreak.Style["display"] = "block";
}
else
{
displayMenuBar.Style["display"] = "none";
displayLineBreak.Style["display"] = "none";
}
loadDisplay();
loadTemplate();
loadTabs();
saveDefaultOneOffFilter();
checkIfEmpty();
RadTab tab = displayTabs.SelectedTab;
Profile.CurrTemplate = Profile.DefaultTemplate;
if (Profile.DefaultTemplate == dfltTempID) //new user
{
displayName.Text = User.Identity.Name + "_default";
si_display_save_button_Click();
setDefault();
Profile.CurrTemplate = Profile.DefaultTemplate;
updateStatsformat();
Response.Redirect("Display.aspx");
}
if (tab != null)
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = tab.Text;
}
}
else
{
RadTab tab = displayTabs.SelectedTab;
if (tab != null)
{
if (tab.Text == Session["SelectedTabID"].ToString())
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
loadDynamicDisplayGrid(Profile.CurrTemplate);//needs to be different, special just for postback
}
else
{
loadDisplayGrid(Profile.CurrTemplate);
Session["SelectedTabID"] = displayTabs.SelectedTab.Text;
}
//automatically saves when toolbar is not visible....
if (!Profile.ShowFilter) { si_display_save_button_Click(); }
}
}
}
/// <summary>
/// updates and loads the RadGrid for the Display page, depending on which Tab is selected
/// </summary>
private void loadDisplayGrid(int tmpid)
{
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
GridTemplateColumn columntxtbx;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
//ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert", "<script>alert('" + Profile.CurrTemplate + "');</script>", false);
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
DataRowView row = (DataRowView)item.DataItem;
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
String value = row["IsDisplayed"].ToString();
chkbx.Checked = (value == "True");
}
}
/// <summary>
/// This is the template for GridTemplateColumn in the display page's grid
/// This represent the column DisplayString
/// Three different kinds of contents are used in each cell of the column depending on StatsValue_Type
/// </summary>
private class MyTemplate : ITemplate
{
//protected RequiredFieldValidator validator1;
//protected RangeValidator validator2;
protected TextBox textBox;
protected DropDownList ddList;
protected Label txtlb;
protected Button up;
protected Button down;
private DisplayGrid.DisplayGridDataTable MyDT = new DisplayGrid.DisplayGridDataTable();
private DisplayGridTableAdapters.DisplayGridTableAdapter MyTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
private Guid myUserID = new Guid();
private int template;
public MyTemplate(DisplayGrid.DisplayGridDataTable DGDT, Guid UserID,int tempid)
{
MyDT = DGDT;
myUserID = UserID;
template = tempid;
}
public void InstantiateIn(System.Web.UI.Control container)
{
//textBox = new TextBox();
ddList = new DropDownList();
txtlb = new Label();
up = new Button();
up.Text = "↑";
down = new Button();
down.Text = "↓";
//textBox.ID = "templateColumnTextBox";
ddList.ID = "templateColumnDDList";
txtlb.ID = "txtLabel";
up.ID = "up";
down.ID = "down";
//textBox.DataBinding += new EventHandler(textBox_DataBinding);
ddList.DataBinding += new EventHandler(ddList_DataBinding);
txtlb.DataBinding += new EventHandler(label_DataBinding);
up.Click += new EventHandler(up_Click);
down.Click += new EventHandler(down_Click);
/*validator1 = new RequiredFieldValidator();
validator1.ControlToValidate = "templateColumnTextBox";
validator1.ErrorMessage = "*";
validator1.Display = ValidatorDisplay.Dynamic;
validator2 = new RangeValidator();
validator2.ControlToValidate = "templateColumnTextBox";
validator2.Type = ValidationDataType.Integer;
validator2.MinimumValue = "0";
validator2.MaximumValue = "12";
validator2.ErrorMessage = "*0-12";
validator2.Display = ValidatorDisplay.Dynamic;*/
//container.Controls.Add(textBox);
container.Controls.Add(ddList);
container.Controls.Add(txtlb);
container.Controls.Add(up);
container.Controls.Add(down);
//container.Controls.Add(validator1);
//container.Controls.Add(validator2);
}
/// <summary>
/// Generates the text boxes when StatsValue_Type is double or percentage
/// Assigns the text and the style
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void textBox_DataBinding(object sender, EventArgs e)
{
TextBox tBox = (TextBox)sender;
GridDataItem container = (GridDataItem)tBox.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "double" || valType == "percentage")
{
tBox.Text = displayStr.Remove(displayStr.IndexOf(" "));
tBox.Font.Bold = true;
tBox.Style["text-align"] = "center";
tBox.Width = 70;
tBox.AutoPostBack = true;
//tBox.TextChanged += new EventHandler(DisplayTextBox_TextChanged);
}
else
{
tBox.Enabled = false;
tBox.Visible = false;
}
}*/
protected void up_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')))+1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
protected void down_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
GridDataItem container = (GridDataItem)bt.NamingContainer;
//ScriptManager.RegisterStartupScript(bt, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
int num = Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' '))) -1;
string updateDisplay = num.ToString() + " decimals";
string updateVal = "{0:f" + num.ToString() + "}";
short stats_id = Convert.ToInt16(rdm);
if (num < 13 && num > -1)
{
MyTA.UpdateQuery(updateVal, updateDisplay, stats_id, (short)template);
}
}
/// <summary>
/// Generates the drop down lists when StatsValue_Type is Date
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ddList_DataBinding(object sender, EventArgs e)
{
DropDownList dl = (DropDownList)sender;
GridDataItem container = (GridDataItem)dl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "Date")
{
dl.Items.Add(new ListItem("MM-DD-YY", "{0:MM-dd-yy}"));
dl.Items.Add(new ListItem("DD-MM-YY", "{0:dd-MM-yy}"));
dl.Items.Add(new ListItem("DD-MMM-YYYY", "{0:dd-MMM-yyyy}"));
dl.SelectedIndex = (displayStr == "MM-DD-YY") ? 0 : (displayStr == "DD-MM-YY") ? 1 : 2;
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
up.Visible = false;
down.Visible=false;
}
/*else if (valType == "double" || valType == "percentage")
{
dl.Items.Add(new ListItem("1 decimals", "{0:f1}"));
dl.Items.Add(new ListItem("2 decimals", "{0:f2}"));
dl.Items.Add(new ListItem("3 decimals", "{0:f3}"));
dl.Items.Add(new ListItem("4 decimals", "{0:f4}"));
dl.Items.Add(new ListItem("5 decimals", "{0:f5}"));
dl.Items.Add(new ListItem("6 decimals", "{0:f6}"));
dl.Items.Add(new ListItem("7 decimals", "{0:f7}"));
dl.Items.Add(new ListItem("8 decimals", "{0:f8}"));
dl.Items.Add(new ListItem("9 decimals", "{0:f9}"));
dl.Items.Add(new ListItem("10 decimals", "{0:f10}"));
dl.Items.Add(new ListItem("11 decimals", "{0:f11}"));
dl.Items.Add(new ListItem("12 decimals", "{0:f12}"));
dl.SelectedIndex =Convert.ToInt32(displayStr.Substring(0, displayStr.IndexOf(' ')));
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(DisplayDDList_IndexChanged);
}*/
else
{
dl.Enabled = false;
dl.Visible = false;
}
}
/// <summary>
/// Generates the words " digits" after the textboxes when StatsValue_Type is double or percentage
/// Generates the label with text of DisplayString when StatsValue_Type is bit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void label_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
GridDataItem container = (GridDataItem)lbl.NamingContainer;
string displayStr = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string valType = ((DataRowView)container.DataItem)[MyDT.Columns[4].ColumnName].ToString();
string rdm = ((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString();
if (valType == "bit")
{
lbl.Text = displayStr;
lbl.Font.Bold = true;
up.Visible = false;
down.Visible = false;
}
else if (valType == "double" || valType == "percentage") {
lbl.Text = displayStr;
lbl.Font.Bold = true;
}
else { lbl.Text = ""; }
}
/// <summary>
/// Handles the event when textbox is sumbitted
/// inefficient at the moment because it is fired for every textbox every tab change
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/*protected void DisplayTextBox_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
GridDataItem container = (GridDataItem)tb.NamingContainer;
string textCur = ((TextBox)sender).Text + " decimals";
string textOld = ((DataRowView)container.DataItem)[MyDT.Columns[1].ColumnName].ToString();
string testing = ((DataRowView)container.DataItem)[MyDT.Columns[0].ColumnName].ToString();
if (textCur != textOld)
{
int value = Convert.ToInt16(((TextBox)sender).Text);
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
string format = "{0:f" + value.ToString() + "}";
string text = value.ToString() + " decimals";
ScriptManager.RegisterStartupScript(tb, typeof(Page), "Alert", "<script>alert('" + "a" + "');</script>", false);
//MyTA.UpdateDisplayGrid(format, text, myUserID, stats_id);
MyTA.UpdateQuery(format, text, stats_id, (short)template);
}
}*/
/// <summary>
/// Handles the event when dropdownlist selection changes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DisplayDDList_IndexChanged(object sender, EventArgs e)
{
string date = ((DropDownList)sender).SelectedItem.Text;
string format = ((DropDownList)sender).SelectedItem.Value;
DropDownList ddl = (DropDownList)sender;
GridDataItem container = (GridDataItem)ddl.NamingContainer;
short stats_id = Convert.ToInt16(((DataRowView)container.DataItem)[MyDT.Columns[3].ColumnName].ToString());
//MyTA.UpdateDisplayGrid(format, date, myUserID, stats_id);
MyTA.UpdateQuery(format, date, stats_id, (short)template);
}
}
//this is called on postback
protected void loadDynamicDisplayGrid(int tmpid)
{
ArrayList oldchkbxList = new ArrayList();
short DType = Convert.ToInt16(displayTabs.SelectedTab.Value);
GridBoundColumn column;
GridColumn columnchkbx;
GridTemplateColumn columntxtbx;
GridButtonColumn columnUp;
GridButtonColumn columnDown;
//GridTemplateColumn columnArrow;
DisplayGrid.DisplayGridDataTable DisplayGridDT = new DisplayGrid.DisplayGridDataTable();
DisplayGridTableAdapters.DisplayGridTableAdapter DisplayGridTA = new DisplayGridTableAdapters.DisplayGridTableAdapter();
//update statsformat for the user if necessary
if (Profile.CurrTemplate != 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDB_ConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("UpdateNewStat", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#userid", SqlDbType.UniqueIdentifier).Value = getUserID();
command.Parameters.Add("#tempid", SqlDbType.SmallInt).Value = Profile.CurrTemplate;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
if (Profile.DefaultTemplate != 0)
{
DisplayGridTA.FillBy(DisplayGridDT, DType, (short)tmpid);
}
if (DisplayGridDT.Rows.Count == 0)
{
DisplayGridTA.Fill(DisplayGridDT, getUserID(), DType);
}
//save the old values of the IsDisplayed checkboxes before refresh
foreach (GridDataItem item in StatsFormatGrid.Items)
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
oldchkbxList.Add(chkbx.Checked);
}
StatsFormatGrid.Columns.Clear();
//Stat IsDisplayed
columnchkbx = new GridCheckBoxColumn();
columnchkbx.HeaderText = "Displayed";
columnchkbx.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnchkbx);
//Stats Name
column = new GridBoundColumn();
column.HeaderText = "Stats Name";
column.DataField = DisplayGridDT.Columns[0].ColumnName;
column.UniqueName = DisplayGridDT.Columns[0].ColumnName;
StatsFormatGrid.Columns.Add(column);
//Invisible columns
for (int i = 3; i <= 6; i++)
{
column = new GridBoundColumn();
column.HeaderText = (i == 3) ? "StatsTable.Stats_id" : (i == 4) ? "StatsTable.StatsValue_Type" : (i == 5) ? "StatsTable.Stats_CHeader" : "StatsTable.Stats_Desc";
column.DataField = DisplayGridDT.Columns[i].ColumnName;
column.UniqueName = DisplayGridDT.Columns[i].ColumnName;
column.Visible = false;
StatsFormatGrid.Columns.Add(column);
}
//Dynamically created column - Stats Display Format
columntxtbx = new GridTemplateColumn();
columntxtbx.HeaderText = "Stats Display Format";
columntxtbx.ItemTemplate = new MyTemplate(DisplayGridDT, getUserID(),Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columntxtbx);
/*
columnArrow = new GridTemplateColumn();
columnArrow.ItemTemplate = new ArrowTemplate(DisplayGridDT, getUserID(), Profile.CurrTemplate);
StatsFormatGrid.Columns.Add(columnArrow);*/
columnUp = new GridButtonColumn();
columnUp.Text = "↑";
columnUp.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnUp);
columnDown = new GridButtonColumn();
columnDown.Text = "↓";
columnDown.UniqueName = DisplayGridDT.Columns[2].ColumnName;
StatsFormatGrid.Columns.Add(columnDown);
StatsFormatGrid.DataSource = DisplayGridDT;
StatsFormatGrid.DataBind();
int itr = 0;
foreach (GridDataItem item in StatsFormatGrid.Items) //sets the properties of IsDisplayed
{
CheckBox chkbx = (CheckBox)item["IsDisplayed"].Controls[0];
chkbx.Enabled = true;
chkbx.AutoPostBack = true;
chkbx.Checked = (Boolean)oldchkbxList[itr];
DataRowView row = (DataRowView)item.DataItem;
String value = row["IsDisplayed"].ToString();
if (value == "True" && !(Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
else if (value != "True" && (Boolean)oldchkbxList[itr])
{
DisplayedCheckbox_CheckedChanged(chkbx, DisplayGridDT);
}
itr++;
}
}
//this is html
<telerik:RadGrid ID="StatsFormatGrid" runat="server" AutoGenerateColumns="False" GridLines="None"
OnDataBound="grid_data_bound" EnableAJAX="true">
<%--ClientSettings>
<Selecting AllowRowSelect="True"></Selecting>
</ClientSettings--%>
</telerik:RadGrid>
I believe you are having a common problem with databinding and the ASP.net Page life cycle. Simply put: you first databind the data and then you change it. The Page_Load event handler binds your data, after that the press of the button is handled and it changes the database. However, the control is already bound to a previous version of the data and displays old information.
You should databind your control AFTER the button press has been handled and the change in the database has been processed. Try putting your databinding code in the Page_PreRender event handler.
You can add
Response.Redirect(Request.RawUrl);
after finish updating database in button click event.
Or call functions that init data in your page. For example
private void Page_Load(...)
{
if(!Page.IsPostBack)
{
InitData();
}
}
private void InitData()
{
//Do init data control in your page
// For exp: binding the grid, combo box....
}
protected void btn_Update_Clicked(...)
{
//1. Update database
//2. Call InitData() function to reload data from database
}
Related
After trying some solutions I can't get it done.
I am reading the access.mdb file and I am populating
the datagridview.
Then I add checkboxcolumn. After it is done you can select some checkboxes and they will be saved in settings. But as I start the prog again the values of the checkboxes are set but they are not drawn. I have tried dataGridView.Refresh(), dataGridView.EndEdit() and so on. Where is my mistake and what I am missing?
public partial class Form1 : Form {
private List<int> listCheckedColumn = new List<int>();
private List<string> listNewNames = new List<string>();
public Form1() {
InitializeComponent();
//Properties.Settings.Default.Reset(); //fürs debugging
if (!Properties.Settings.Default["pathOpenings"].Equals("leer") && !Properties.Settings.Default["pathProfiles"].Equals("leer")) {
loadOutputData();
//update RESULT Tabelle
}
if (!Properties.Settings.Default["naSysID"].Equals("leer")) {
updateListCheckedColumnFromSettings();
updateCheckboxes();
//update die RESULT Tabelle
}
if (!Properties.Settings.Default["newNames"].Equals("leer")) {
//fülle die new name Liste
//fülle die zellen mit infos
//update die RESULT Tabelle
}
}
private void updateCheckboxes() {
foreach (int value in listCheckedColumn) {
int rowIndex = getRowIndexWithValueX(value);
if (Convert.ToInt32(dataGridView3.Rows[rowIndex].Cells["SystemID"].Value) == value) {
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView3.Rows[rowIndex].Cells["Nicht beachten"];
checkbox.Value = checkbox.TrueValue;
MessageBox.Show("Row:" + checkbox.RowIndex + " Column:" + checkbox.ColumnIndex);
}
}
}
...
...
/// <summary>
///
/// </summary>
internal void loadOutputData() {
var connOpenings = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Properties.Settings.Default["pathOpenings"] + ";");
var connProfiles = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Properties.Settings.Default["pathProfiles"] + ";");
...
//
// System aka System Names Table
//
var sysNames = new DataTable();
var adapterSysNames = new OleDbDataAdapter("SELECT SystemID, SystemName FROM Systems;", connProfiles);
adapterSysNames.Fill(sysNames);
dataGridView3.DataSource = sysNames;
dataGridView3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView3.Sort(dataGridView3.Columns[0], ListSortDirection.Ascending);
DataGridViewCheckBoxColumn checkedColumn = new DataGridViewCheckBoxColumn();
checkedColumn.Name = "Nicht beachten";
checkedColumn.FalseValue = false;
checkedColumn.TrueValue = true;
dataGridView3.Columns.Add(checkedColumn);
dataGridView3.CellValueChanged += new DataGridViewCellEventHandler(dataGridView3_CellValueChanged);
dataGridView3.CurrentCellDirtyStateChanged += new System.EventHandler(dataGridView3_CurrentCellDirtyStateChanged);
}
...
private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
if (e.ColumnIndex == dataGridView3.Columns["Nicht beachten"].Index) {
int cellValue = Convert.ToInt32(dataGridView3.Rows[e.RowIndex].Cells["SystemID"].Value);
DataGridViewCheckBoxCell checkbox = (DataGridViewCheckBoxCell)dataGridView3.Rows[e.RowIndex].Cells["Nicht beachten"];
if (checkbox.Value == checkbox.TrueValue) {
if (!isInList(listCheckedColumn, cellValue)) {
listCheckedColumn.Add(cellValue);
listCheckedColumn.Sort();
Properties.Settings.Default["naSysID"] = makeStringFromIntList();
Properties.Settings.Default.Save();
}
} else {
if (isInList(listCheckedColumn, cellValue)) {
listCheckedColumn.Remove(cellValue);
listCheckedColumn.Sort();
Properties.Settings.Default["naSysID"] = makeStringFromIntList();
Properties.Settings.Default.Save();
}
}
}
foreach (DataGridViewRow row in dataGridView3.Rows) {
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["Nicht beachten"];
if (chk.Value == chk.TrueValue) {
MessageBox.Show("Checked- Row: " + chk.RowIndex + " Column: " + chk.ColumnIndex);
}
}
}
...
private void dataGridView3_CurrentCellDirtyStateChanged(object sender, EventArgs e) {
if (dataGridView3.IsCurrentCellDirty && dataGridView3.CurrentCell.ColumnIndex == dataGridView3.Columns["Nicht beachten"].Index) {
dataGridView3.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
...
...
}
have you tried with dataGridView.Update()? Maybe that works.
I am new to windows application.I have a table in which there are two fields namely,Title and Type.
In Type field i have two values "O" & "T".
Now i have to populate a datagrid with this table Title as first column and in second column depending on the Type field value i have to place a control i.e when Type field will have "O" at that time i have to place a combobox in that column and when it is "T" i have to place a text Box
i have tried a lot and googled a lot but both controls in same column is quite difficult for me as a beginner.
Plz help me with this requirement.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ERP_Ship.App_Code.Fleet_Person;
using ERP_Ship.App_Code.Appraisal;
using ERP_Ship.Forms.Master;
using ERP_Ship.App_Code.Common;
using ERP_Ship.App_Code.Vessel_Hardening_Measures;
namespace ERP_Ship.Forms.Reports
{
public partial class Vessel_Hardening_Measures : Form
{
// ? //
private DataSet ds = new DataSet("myDs");
private DataTable dt = new DataTable("Apprdtl");
//Define controls must be add to data grid.
private Label lblControl = new Label();
private TextBox txtControl = new TextBox();
private ComboBox cboControl = new ComboBox();
//Capture the clicked cell
private DataGrid.HitTestInfo hitTestGrid;
//Control definishion to add to DataGrid
DataGridTableStyle dataGridStyle = new DataGridTableStyle();
DataGridTextBoxColumn dataGridLableTitle = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle1 = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridLableTitle2 = new DataGridTextBoxColumn();
//DataGridTextBoxColumn dataGridLable = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridTextBox = new DataGridTextBoxColumn();
DataGridTextBoxColumn dataGridComboBox = new DataGridTextBoxColumn();
private System.Windows.Forms.DataGrid gv_Appraisal;
#region Form Level Variables
string _strName;
string _strCDCNo;
//DataTable dt = new DataTable();
// OracleConnection con1 = new OracleConnection(ConfigurationManager.ConnectionStrings["MySQLConnection"].ConnectionString.ToString());
I_Common objCommon = new I_Common();
DataTable dt1 = new DataTable("dt1");
#endregion
#region Public Properties
public string SearchName
{
set
{
_strName = value;
}
get
{
return _strName;
}
}
public string SearchCDCNo
{
set
{
_strCDCNo = value;
}
get
{
return _strCDCNo;
}
}
#endregion
public Vessel_Hardening_Measures()
{
InitializeComponent();
InitializeControls();
Load_Year();
//for (int index = 0; index <= gv_Appraisal.Columns.Count - 1; index++)
//{
// gv_Appraisal.Columns[index].DataPropertyName = gv_Appraisal.Columns[index].Name;
//}
//gv_Appraisal.AutoGenerateColumns = false;
}
private void InitializeControls()
{
//label property
lblControl.Cursor = Cursors.Hand;
lblControl.ForeColor = Color.Red;
lblControl.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
//textbox property
txtControl.Cursor = Cursors.Hand;
txtControl.BackColor = Color.WhiteSmoke;
txtControl.ForeColor = Color.DarkSlateBlue;
txtControl.Font = new Font("Arial", 8, FontStyle.Bold);
//textbox events.
txtControl.TextChanged += new EventHandler(txtTextChanged);
string[] dropdownitems = { "Yes", "No", "Not Applicable" };
//Define and add ComboBox rows, will be added to data grid.
for (int i = 0; i < dropdownitems.Count(); i++)
cboControl.Items.Add(dropdownitems[i]);
//combobox property
cboControl.Cursor = Cursors.Hand;
cboControl.DropDownStyle = ComboBoxStyle.DropDownList;
//combobox events.
cboControl.SelectedIndexChanged += new EventHandler(cboSelectedIndexChanged);
}
private void DesignTableStyle()
{
dataGridStyle.PreferredRowHeight = 24;
dataGridStyle.MappingName = "Apprdtl";
gv_Appraisal.TableStyles.Add(dataGridStyle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle1);
dataGridStyle.GridColumnStyles.Add(dataGridLableTitle2);
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
//dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridLableTitle.HeaderText = "vhm_id";
dataGridLableTitle.MappingName = "vhm_id";
dataGridLableTitle.Width = 1;
//dataGridLableTitle.Width = 40;
dataGridLableTitle1.HeaderText = "Title";
dataGridLableTitle1.MappingName = "Title";
dataGridLableTitle1.Width = 150;
dataGridLableTitle2.HeaderText = "Type";
dataGridLableTitle2.MappingName = "Type";
dataGridLableTitle2.Width = 1;
//dataGridLableTitle2.Width = 40;
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//dataGridComboBox.HeaderText = "COMBOBOX_COL";
//dataGridComboBox.MappingName = "ComboBox_col";
//dataGridComboBox.Width = 130;
}
private void Load_DNF() // DATA NOT FOUND OF CDC NO
{
try
{
using (BL_Vessel_Hardening_Measures obj_vsl_hardening_measures = new BL_Vessel_Hardening_Measures())
{
DataTable dataTable = new DataTable();
ds = obj_vsl_hardening_measures.Get_Vessel_Hardening_Measures();
dt1 = ds.Tables[0];
DataColumn dc = new DataColumn("vhm_id");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Title");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
dc = new DataColumn("Type");
//Add created column to datatable object.
dt.Columns.Add(dc);
//Create a new column for datatable.
//Create a new column for datatable.
dc = new DataColumn("TextBox_Col", System.Type.GetType("System.String"));
//Add created column to datatable object.
dt.Columns.Add(dc);
DataRow dr;
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt.NewRow();
dr["vhm_id"] = dt1.Rows[i]["vhm_id"];
dr["Title"] = dt1.Rows[i]["Title"];
dr["Type"] = dt1.Rows[i]["Type"];
dr["TextBox_Col"] = "";
//dr["ComboBox_Col"] = "";
dt.Rows.Add(dr);
}
// gv_Appraisal.DataSource = ds.Tables[0];
gv_Appraisal.DataSource = dt;
ds.Tables.Remove("Apprdtl");
ds.Tables.Add(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
cls_Utility.Close_Pending_Form();
Home objHome = new Home();
I_Common.CloseForm(this.MdiParent, this, objHome);
}
private void Reset_Controls()
{
//txt_CDC_NO.Text = "";
//cmb_Name.SelectedIndex = -1;
}
~Vessel_Hardening_Measures()
{
this.Close();
}
private void Vessel_Hardening_Measures_FormClosed(object sender, FormClosedEventArgs e)
{
cls_Utility.Close_Pending_Form();
}
private void Load_Year()
{
try
{
//ddl_Year.DisplayMember = "Year";
//ddl_Year.ValueMember = "Year";
objCommon.Load_Years(ddl_Year, 1);
//string str_year = "";
//str_year = DateTime.Now.AddYears(-1).Year.ToString();
//ddl_Year.Items.Add(str_year);
//str_year = DateTime.Now.Year.ToString();
//ddl_Year.Items.Add(str_year);
// ddl_Year.SelectedIndex = 1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Vessel_Hardening_Measures_Load(object sender, EventArgs e)
{
DesignTableStyle();
Load_DNF();
ERP_Ship.App_Code.Common.I_Common.MdiFormTopPanel("Vessel Hardening Measures", "Vessel Hardening Measures", this.MdiParent, true);
//ERP_Ship.App_Code.Common.I_Common.StatusInfoLabel("Double Click the Search Record to View or Edit", "I", this.MdiParent, true);
}
private void gv_Appraisal_MouseUp(object sender, MouseEventArgs e)
{
hitTestGrid = gv_Appraisal.HitTest(e.X, e.Y);
if (hitTestGrid != null)
{
//Which column of datagrid has been clicked.
//switch (hitTestGrid.Column)
//{
if (hitTestGrid.Column == 3)
{
if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "T")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridTextBox);
dataGridTextBox.HeaderText = "TEXTBOX_COL";
dataGridTextBox.MappingName = "TextBox_Col";
dataGridTextBox.Width = 130;
//Add texbox control to datagrid.
dataGridTextBox.TextBox.Controls.Add(txtControl);
// txtControl.Text = gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString();
txtControl.Focus();
}
else if (gv_Appraisal[gv_Appraisal.CurrentRowIndex, 2].ToString() == "O")
{
dataGridStyle.GridColumnStyles.Clear();
dataGridStyle.GridColumnStyles.Add(dataGridComboBox);
dataGridComboBox.HeaderText = "COMBOBOX_COL";
dataGridComboBox.MappingName = "ComboBox_col";
dataGridComboBox.Width = 130;
//Add combobox control to datagrid.
dataGridComboBox.TextBox.Controls.Add(cboControl);
cboControl.Focus();
//for (int i = 0; i < cboControl.Items.Count; i++)
//{
// if (cboControl.Items[i].ToString() == gv_Appraisal[gv_Appraisal.CurrentRowIndex, 3].ToString())
// cboControl.SelectedIndex = i;
//}
}
}
}
}
private void txtTextChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = txtControl.Text;
}
//Combobox selected index changed event.
private void cboSelectedIndexChanged(object sender, System.EventArgs e)
{
ds.Tables["Apprdtl"].Rows[gv_Appraisal.CurrentRowIndex]["TextBox_Col"] = cboControl.Text;
}
}
}
There might be multiple approaches to implement functionality, you are looking for.
I found one sample on this link
Check if approach described there suits to your current requirement needs.
I am able to generate dynamic web controls based on DropDownlist selected input. I need to implement a button click event which should walk through all the inputs from those dynamic web controls and display the results in JQGrid Table.
Requirement: How to retain all the input texts from those dynamic web controls using SavedViewState() and LoadViewState(). I am new to dynamic web controls and Viewstates. Help needed
I have given my complete sample code.
My C# Code:
private void BindDropDownLists()
{
column_list_for_filter.ConnectionString = connection;
string item = "--Select--";
column_list_for_filter.SelectCommand = "SELECT DATA_TYPE + '_' + convert(varchar(10), ROW_NUMBER() OVER(ORDER BY DATA_TYPE))as DATA_TYPE, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'RESULT' AND COLUMN_NAME IN ('Column1','Column2','Column3','Column4'))";
DropDownList5.DataTextField = "COLUMN_NAME";
DropDownList5.DataValueField = "DATA_TYPE";
DropDownList5.DataBind();
DropDownList5.Items.Insert(0, item);
}
protected void createdynamiccontrols_decimal()
{
int i = DropDownList5.SelectedIndex;
++i;
TableRow row = new TableRow();
row.ID = "TableRow_";
TableCell cell1 = new TableCell();
cell1.ID = "TableCell_";
DropDownList Range_DDL_Decimal = new DropDownList();
Range_DDL_Decimal.ID = "RandeDDL_Decimal" + i.ToString();
Range_DDL_Decimal.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL_Decimal.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL_Decimal.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL_Decimal.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL_Decimal.Items.Insert(4, new ListItem("lesser than", "lesser than"));
Range_DDL_Decimal.Items.Insert(5, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL_Decimal.Items.Insert(6, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL_Decimal.Items.Insert(7, new ListItem("Contains", "Contains"));
Range_DDL_Decimal.Items.Insert(8, new ListItem("Is Null", "Is Null"));
Range_DDL_Decimal.Items.Insert(9, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL_Decimal.Items.Insert(10, new ListItem("Between", "Between"));
Range_DDL_Decimal.AutoPostBack = true;
Range_DDL_Decimal.SelectedIndexChanged += new System.EventHandler(Range_DDL_Decimal_SelectedIndexChanged);
cell1.Controls.Add(Range_DDL_Decimal);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Range_DDL_Decimal_SelectedIndexChanged(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
TableCell cell2 = new TableCell();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lbl1 = new Label();
Label lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
cell2.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
TableRow rowtwo = dynamic_filter_table.FindControl("TableRow_") as TableRow;
rowtwo.Cells.Add(cell2);
dynamic_filter_table.Rows.Add(rowtwo);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected override object SaveViewState()
{
/***1. Retain DDL 1 selected text
2. Retain DDL 2 selected text DDL2 generated by DDL 1
3. Retain Tb1.text and tb2.text generated by DDL2 ***/
//How to Proceed
}
protected override void LoadViewState(object savedState)
{
//How to Proceed
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
//Find Control not working
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
con.Open();
// **How to pass values to this query from savedstate**
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RESULT WHERE " + DropDownList5.Text + DDL2.Text + " >= " + lowerboundd.Text + " AND " + DropDownList5.Text + " <= " + upperbound.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
if (!IsPostBack)
{
BindDropDownLists();
}
else
{
if (!String.IsNullOrEmpty(DropDownList5.SelectedValue))
{
if (DropDownList5.SelectedValue.Contains("decimal"))
{
createdynamiccontrols_decimal();
}
else if (DropDownList5.SelectedValue.Contains("varchar"))
{
createdynamiccontrols_varchar();
}
else if (DropDownList5.SelectedValue.Contains("datetime"))
{
createdynamiccontrols_datetime();
}
else if (DropDownList5.SelectedValue.Contains("int"))
{
createdynamiccontrols_int();
}
}
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
else
{
if (!String.IsNullOrEmpty(DropDownList5.SelectedValue))
{
if (DropDownList5.SelectedValue.Contains("decimal"))
{
createdynamiccontrols_decimal();
}
else if (DropDownList5.SelectedValue.Contains("varchar"))
{
createdynamiccontrols_varchar();
}
else if (DropDownList5.SelectedValue.Contains("datetime"))
{
createdynamiccontrols_datetime();
}
else if (DropDownList5.SelectedValue.Contains("int"))
{
createdynamiccontrols_int();
}
}
}
You don't need to override SaveViewState/LoadViewState. But you have to keep selections in ViewState to create controls on postback. This should work:
internal enum DataType
{
None = 0,
Decimal
}
internal enum Operator
{
Equal,
GreaterThan,
None
}
public partial class _Default : Page
{
private DataType DataType
{
get
{
object dataType = ViewState["DataType"];
if (dataType != null) return (DataType)dataType;
return DataType.None;
}
set { ViewState["DataType"] = value; }
}
private int? DataTypeIndex
{
get { return ViewState["DataTypeIndex"] as int?; }
set { ViewState["DataTypeIndex"] = value; }
}
private Operator Operator
{
get
{
var #operator = ViewState["Operator"];
if (#operator != null)
return (Operator)#operator;
return Operator.None;
}
set { ViewState["Operator"] = value; }
}
private void BindDropDownLists()
{
column_list_for_filter.ConnectionString = connection;
string item = "--Select--";
column_list_for_filter.SelectCommand = "SELECT DATA_TYPE + '_' + convert(varchar(10), ROW_NUMBER() OVER(ORDER BY DATA_TYPE))as DATA_TYPE, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'RESULT' AND COLUMN_NAME IN ('Column1','Column2','Column3','Column4'))";
DropDownList5.DataTextField = "COLUMN_NAME";
DropDownList5.DataValueField = "DATA_TYPE";
DropDownList5.DataBind();
DropDownList5.Items.Insert(0, item);
}
protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTypeIndex = DropDownList5.SelectedIndex;
if (DropDownList5.SelectedValue.Contains("decimal"))
{
DataType = DataType.Decimal;
}
CreateDataTypeControl();
//else if (DropDownList5.SelectedValue.Contains("varchar"))
//{
//DataType = DataType.Varchar;
//}
//else if (DropDownList5.SelectedValue.Contains("datetime"))
//{
//DataType = DataType.DateTime;
//}
//else if (DropDownList5.SelectedValue.Contains("int"))
//{
//DataType = DataType.Integer;
//}
}
protected void Range_DDL_Decimal_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
switch (ddl.SelectedIndex)
{
case 1:
Operator = WebApplication1.Operator.Equal;
break;
}
CreateRangeControls();
}
protected void createdynamiccontrols_decimal()
{
int i = DataTypeIndex.GetValueOrDefault();
++i;
TableRow row = new TableRow();
row.ID = "TableRow_";
TableCell cell1 = new TableCell();
cell1.ID = "TableCell_";
DropDownList Range_DDL_Decimal = new DropDownList();
Range_DDL_Decimal.ID = "RandeDDL_Decimal" + i.ToString();
Range_DDL_Decimal.Items.Insert(0, new ListItem("--Select--", "--Select--"));
Range_DDL_Decimal.Items.Insert(1, new ListItem("Equal", "Equal"));
Range_DDL_Decimal.Items.Insert(2, new ListItem("NotEqual", "NotEqual"));
Range_DDL_Decimal.Items.Insert(3, new ListItem("greater than", "greater than"));
Range_DDL_Decimal.Items.Insert(4, new ListItem("lesser than", "lesser than"));
Range_DDL_Decimal.Items.Insert(5, new ListItem("greater than or equal to", "greater than or equal to"));
Range_DDL_Decimal.Items.Insert(6, new ListItem("lesser than or equal to", "lesser than or equal to"));
Range_DDL_Decimal.Items.Insert(7, new ListItem("Contains", "Contains"));
Range_DDL_Decimal.Items.Insert(8, new ListItem("Is Null", "Is Null"));
Range_DDL_Decimal.Items.Insert(9, new ListItem("Is Not Null", "Is Not Null"));
Range_DDL_Decimal.Items.Insert(10, new ListItem("Between", "Between"));
Range_DDL_Decimal.SelectedIndexChanged += new System.EventHandler(Range_DDL_Decimal_SelectedIndexChanged);
Range_DDL_Decimal.AutoPostBack = true;
cell1.Controls.Add(Range_DDL_Decimal);
//// Add the TableCell to the TableRow
row.Cells.Add(cell1);
dynamic_filter_table.Rows.Add(row);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void CreateRangeTextBoxes()
{
int j = DataTypeIndex.GetValueOrDefault();
++j;
TableCell cell2 = new TableCell();
cell2.ID = "Range";
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lbl1 = new Label();
Label lbl2 = new Label();
// Set a unique ID for each TextBox added
tb1.ID = "lowerbound_" + j.ToString();
tb2.ID = "upperbound_" + j.ToString();
lbl1.Text = "LowerBound:";
lbl1.Font.Size = FontUnit.Point(10);
lbl1.Font.Bold = true;
lbl1.Font.Name = "Arial";
lbl2.Text = "UpperBound:";
lbl2.Font.Size = FontUnit.Point(10);
lbl2.Font.Bold = true;
lbl2.Font.Name = "Arial";
cell2.Controls.Add(lbl1);
cell2.Controls.Add(tb1);
cell2.Controls.Add(lbl2);
cell2.Controls.Add(tb2);
TableRow rowtwo = dynamic_filter_table.FindControl("TableRow_") as TableRow;
rowtwo.Cells.Add(cell2);
dynamic_filter_table.Rows.Add(rowtwo);
dynamic_filter_table.EnableViewState = true;
ViewState["dynamic_filter_table"] = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = DropDownList5.SelectedIndex;
++j;
Panel6.Visible = true;
JQGrid9.Visible = true;
Find Control not working
TextBox lowerboundd = dynamic_filter_table.FindControl("lowerbound_" + j.ToString()) as TextBox;
TextBox upperbound = dynamic_filter_table.FindControl("upperbound_" + j.ToString()) as TextBox;
DropDownList range = dynamic_filter_table.FindControl("RandeDDL_Decimal" + j.ToString()) as DropDownList;
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RESULT WHERE " + DropDownList5.Text + DDL2.Text + " >= " + lowerboundd.Text + " AND " + DropDownList5.Text + " <= " + upperbound.Text, con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
Session["DataforSearch"] = ds.Tables[0];
}
protected void Page_Load(object sender, EventArgs e)
{
Panel6.Visible = false;
JQGrid9.Visible = false;
if (Session["DataforSearch"] != null)
{
Panel6.Visible = true;
JQGrid9.Visible = true;
JQGrid9.DataSource = Session["DataforSearch"] as string;
}
CreateDataTypeControl();
CreateRangeControls();
}
void CreateDataTypeControl()
{
switch (DataType)
{
case DataType.Decimal:
createdynamiccontrols_decimal();
break;
}
}
void CreateRangeControls()
{
switch (Operator)
{
case WebApplication1.Operator.GreaterThan:
case Operator.Equal:
CreateRangeTextBoxes();
break;
}
}
}
I have a web page with multiple Drop Down list created at run time using Template fiels in GridView.
I have assigned event handler to DDL on selectedindexchange event.
But this event handler function is getting called only once and my gridview is getting updated only once.
How do I make my event handler function be called after every selection index change.
Here is MY Code
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("empName"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Insert(y, linkF);
y++;
}
else if (coloumn.ColumnName.Equals("empName"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Insert(y, bfield);
y++;
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa,String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "",conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
}
Mu Event Handler function dp_selected is called only Once. I have called my GridBind() function in Page_Load().
Any help would be highly appreciated.
Thanks in Advance
I'm adding a set of controls to a placeholder on a button's click event. I can add the control once, but on the second time I get this message. I am using the Ajax Toolkit to make some custom controls.
System.InvalidOperationException occurred
Message=Extender controls may not be registered after PreRender.
Source=System.Web.Extensions
StackTrace:
at System.Web.UI.ScriptControlManager.RegisterExtenderControl[TExtenderControl](TExtenderControl extenderControl, Control targetControl).
The code is below:
/// <summary>
/// Handles the Click event of the AddWitnessButton control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
/// <remarks></remarks>
protected void AddWitnessButton_Click(object sender, EventArgs e)
{
int count = Convert.ToInt32(WitnessCountHiddenField.Value);
var fullNameTextBoxId = "FullNameEnhancedTextBox" + count;
var mobileFilteredTextBoxId = "MobileFilteredTextBox" + count;
IList<Panel> oldPanels = (IList<Panel>)Session["WitnessPanels"] ?? new List<Panel>();
//Container
Panel panel = new Panel();
//Seperator
Literal hr = new Literal { Text = "<HR/>" };
//Full Name
Label fullNameLabel = new Label
{
ID = fullNameTextBoxId + "_Label",
AssociatedControlID = fullNameTextBoxId,
Text = "Full Name:"
};
EnhancedTextBox fullNameEnhancedTextBox = new EnhancedTextBox
{
ID = fullNameTextBoxId,
Required = true,
RequiredErrorText = "Full Name is a required field."
};
//Mobile
Label mobileLabel = new Label
{
ID = mobileFilteredTextBoxId + "_Label",
AssociatedControlID = mobileFilteredTextBoxId,
Text = "Mobile:"
};
FilteredTextBox mobileFilteredTextBox = new FilteredTextBox
{
ID = mobileFilteredTextBoxId,
FilterMode = FilterModes.ValidChars,
ValidChars = "0123456789+()",
Required = true,
RequiredErrorText = "Mobile is a required field."
};
//Readd previously added panels
foreach (var addedPanel in oldPanels)
{
AddWitnessPlaceHolder.Controls.Add(addedPanel);
}
//Add new controls to the form
Panel newPanel = new Panel();
newPanel.Controls.Add(hr);
newPanel.Controls.Add(fullNameLabel);
newPanel.Controls.Add(fullNameEnhancedTextBox);
newPanel.Controls.Add(mobileLabel);
newPanel.Controls.Add(mobileFilteredTextBox);
AddWitnessPlaceHolder.Controls.Add(newPanel);
//Increment the ID count
count++;
WitnessCountHiddenField.Value = count.ToString();
//Save the panel to the Session.
oldPanels.Add(newPanel);
Session["WitnessPanels"] = oldPanels;
//Go back to the same wizard step.
ShowStep2HiddenField.Value = "false";
ShowStep3HiddenField.Value = "true";
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(IsPostBack)
{
//Readd previously added panels
var vehicleControls = (IList<Panel>)Session["VehiclePanels"] ?? new List<Panel>();
if (vehicleControls.Any())
{
foreach (var addedPanel in vehicleControls)
{
AddVehiclePlaceholder.Controls.Add(addedPanel);
}
}
var witnessControls = (IList<Panel>)Session["WitnessPanels"] ?? new List<Panel>();
if (witnessControls.Any())
{
foreach (var addedPanel in witnessControls)
{
AddWitnessPlaceHolder.Controls.Add(addedPanel);
}
}
}
}