Update database when Button Event is click? - c#

I can't update my database when my checkbox is checked and click the Validate Button. Note:(I use Session to my pass my Data page by page)
In this another code behind page, I add a column checkbox to my gridview.
//Add a colum check row
SubjectlistTable.Columns.Add("Check", Type.GetType("System.Boolean"));
Session["ValidateSubject"] = SubjectlistTable;
Response.Redirect("ValidateSubjectTeacher.aspx");
In the ValidateSubjectTeacherPage:
This is the program
Aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ValidateSubjectTeacher.aspx.cs" Inherits="SoftwareAnalysisAndDesign.SAD.ValidateSubjectTeacher" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Assessment Form</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="Bootstrap/css/bootstrap-theme.css" />
<link rel="stylesheet" href="Bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Stylesheets/ValidateSubjectTeacherStyle.css"/>
<!--Side bar link-->
<link rel="stylesheet" href="SidebarBootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="SidebarBootstrap/css/simple-sidebar.css" />
</head>
<body>
<form id="form1" runat="server">
<div class="headerwrapper">
<div id="headercontent" class="jumbotron">
<img id="img1" src="usjrlogo.png" />
<h1 id="title">Online AppSess System</h1>
</div>
</div>
<div class="container" style="text-align: center; margin: 0 auto;">
<br />
<h1>Validation of Subjects</h1>
<br />
<asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
</div>
<div style="float: right; padding-right: 75px;">
<button type="button" runat="server" class="btn btn-primary" onserverclick="ValidateSubject_Click">Validate</button>
<button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
</div>
</form>
<script src="jquery/jquery.min.js"></script>
<script src="Bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
Aspx Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//Add a checkbox in the last row of GridView Progmatically
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
}
}
protected void GoBackTeacher_Click(object sender, EventArgs e)
{
Response.Redirect("TeacherPage.aspx");
}
}
}
The code is working but when I click the submit button, the system prompts me with an error and I can't update my database:
Error message:
An exception of type 'System.InvalidCastException' occurred in
SoftwareAnalysisAndDesign.dll but was not handled in user code
Additional information: Unable to cast object of type
'System.Web.UI.HtmlControls.HtmlButton' to type
'System.Web.UI.WebControls.CheckBox'.
There's something wrong with my checkbox event here:
CheckBox chk = (CheckBox)sender;
It seems that checkbox event and button event can't be simultaneously handled.
Please help, this is the only problem I want to fix so that my System is fully working.
Related link Get specific data and update database

When you click on the button, the "event" you are handling isn't coming from the CheckBox in your GridView. It's coming from your <button> element.
The way your application is architected, it seems, you have no need of a button -- any time you click on a checkbox to select or unselect it it will perform the action on that single row of data. So it's unclear what you want to happen when the button is pressed.
You could serve both these events in the same method, if you wished to, by at the start of it doing something like:
protected void ValidateSubject_Click(object sender, EventArgs e) {
if ( sender.GetType().FullName == "System.Web.UI.WebControls.CheckBox" ) {
// Have what you currently have for checkboxes here
} else if ( sender.GetType().FullName == "System.Web.UI.HtmlControls.HtmlButton" ) {
// Do something else for the button, probably involving getting the GridView's rows and iterating through them
}
}
But I would suggest having separate event handlers for the separate events.

Related

How to Bind and Insert in Repeater control in Asp.net?

I have created the table cm_table and cm_table_copy on MySQL database.
On cm_table I have recorded three rows, instead the cm_table_copy is empty
After that added new web form to website.
Drag and drop a Repeater control from Toolbox>Data to .aspx page.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Repeater.aspx.cs" Inherits="Repeater" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="repcomment" runat="server">
<ItemTemplate>
<fieldset>
<legend style="font-size: 12px; font-weight: bold; color: Red; margin-left: 10px;">
Repeater control in Asp.net
</legend>
<div class="pure-g">
<div class="pure-u-1 pure-u-md-1-3">
Comment
<asp:TextBox ID="txComment" runat="server" Text='<%#Eval("Comment").ToString()%>'>
</asp:TextBox>
</div>
</div>
<br />
<div class="container">
<asp:ImageButton ID="btn" runat="server" ValidationGroup="Validation2"
OnClick="btn_Click"
ImageUrl="/Images/edit_button.gif"
OnClientClick="if (!confirm('Confirm?')) return false;"
CausesValidation="true" />
</div>
</fieldset>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<asp:ValidationSummary ID="ValidationSummary1"
ValidationGroup="Validation2" runat="server"
ShowSummary="false"
ShowMessageBox="true"
CssClass="validation-summary-errors" />
</form>
</body>
</html>
I should see on the web browser the three rows recorded on cm_table and when the comment on cm_table is edited I need register the new comment on cm_table_copy
But I have this error on first access to aspx page
CS0103: The name 'txComment' does not exist in the current context
How to do resolve this?
My code-behind below
Can you help me, please?
Thank you in advance for any help
using System;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web.UI;
public partial class Repeater : Page
{
protected void btn_Click(object sender, ImageClickEventArgs e)
{
string sql = String.Format(" INSERT INTO cm_table_copy (Comment, LatestComment) ");
sql += String.Format(" VALUES(?, CURRENT_TIMESTAMP()); ");
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ca"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Parameters.AddWithValue("param1", txComment.Text.Replace("'", "`").ToString().ToUpper()); //<<<Line of error
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sql = #String.Format(" SELECT * FROM cm_table; ");
using (OdbcConnection myConnectionString =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ca"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, myConnectionString))
{
try
{
command.Connection.Open();
DataSet ds = new DataSet();
OdbcDataAdapter adp = new OdbcDataAdapter(command);
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
repcomment.DataSource = ds;
repcomment.DataBind();
}
}
catch (Exception ex)
{
throw new ApplicationException("operation failed!", ex);
}
finally
{
command.Connection.Close();
}
}
}
}
}
}
Update #01
I have tried this but the FindControl always returns null
protected void btn_Click(object sender, ImageClickEventArgs e)
{
TextBox txComment = (TextBox)repcomment.FindControl("txComment");
}

ASP.NET C# The Wait Operation Timed Out

Getting an error that has crashed my entire site. The wait operation is timing out, i have read the documentation on using{} blocks but cannot understand why this is happening. Any help is appreciated.
[Win32Exception (0x80004005): The wait operation timed out]
The page i have been working on most recently is
itemediting.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="itemediting.aspx.cs" Inherits="admin_itemediting" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>elmtree - Admin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../styles/mylist.css" />
</head>
<body>
<form id="form1" runat="server">
<img src="images/ELleft.png" style="width:226px; height:52px; margin-top: 3px; margin-left: 17px; text-align: justify; float: none;"/></a></li>
<div class="container">
<h1> Item Edit </h1> </div>
<div class="container">
<div class="form-group">
<label class="col-sm-2 control-label">Item name: </label>
<div class="col-md-4">
<asp:TextBox ID="itemnametext" runat="server" Text="" CssClass="form-control">
</asp:TextBox>
</div>
<div class="pull-right">
<asp:Button CssClass="btn btn-primary btn-lg" ID="updatebutton" role="button" runat="server" Text="save" OnClick="updatebutton_Click" />
</div>
</div>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class admin_itemediting : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int row = 0;
if (Request.QueryString["itemID"] != null)
{
row = int.Parse(Request.QueryString["itemID"]);
}
else
{
Response.Redirect("itemedit.aspx");
}
}
string connectionString = WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string query = "SELECT * FROM reports WHERE ID=#rowid";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#rowid", row);
SqlDataReader rdr = myCommand.ExecuteReader();
while (rdr.Read())
{
string myname = rdr["itemname"].ToString();
itemnametext.Text = myname;
}
}
protected void updatebutton_Click(object sender, EventArgs e){
string connectionString = WebConfigurationManager.ConnectionStrings ["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
string itemnametextupdate = itemnametext.Text;
string query = "UPDATE reports SET itemname = #itemnewname";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#itemnewname", itemnametextupdate);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("updateimage.aspx");
}
public object row { get; set; }
}
Just a suggestion.
if (!IsPostBack)
{
int row = 0;
if (Request.QueryString["itemID"] != null)
{
row = int.Parse(Request.QueryString["itemID"]);
}
else
{
// here even if you make redirect the code continue to run
// and you do not know whats going on then... a call to db and a redirect.
Response.Redirect("itemedit.aspx");
// so here add a return;
return;
}
}
Next possible bug is that on post back the row is not saved on viewstate and take a default value. Make your row variable as:
int cRow
{
set
{
ViewState["cRow"] = value;
}
get
{
if (ViewState["cRow"] != null)
return Convert.ToInt32(ViewState["cRow"]);
else
return -1;
}
}

JQGrid in asp.net not displaying data (not visible)

I'm following this example and I'm having some hard time displaying data in a gridview. When the page is loaded it gets to GetData and returns values.
If in the immediate windows after I fill datatable and see the count ?dtResult.Rows.Count I get 1001. So I know I have data.
However, when the I debug the app I just get the three buttons. What am I missing here?
Here's the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="TestApp.test" %>
<%# Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<!DOCTYPE html>
<html lang="en-us">
<head id="Head1" runat="server">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/redmond/jquery-ui.css" />
<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />
<!-- jQuery runtime minified -->
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-2.0.3.min.js" type="text/javascript"></script>
<!-- The localization file we need, English in this case -->
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<style type="text/css">
body, html { font-size: 80%; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="message">
<script type="text/javascript">
function addRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
grid.editGridRow("new", grid.addDialogOptions);
}
function editRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
var editOptions = grid.getGridParam('editDialogOptions');
if (rowKey) {
grid.editGridRow(rowKey, editOptions);
}
else {
alert("No rows are selected");
}
}
function delRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
if (rowKey) {
grid.delGridRow(rowKey, grid.delDialogOptions);
}
else {
alert("No rows are selected");
}
}
</script>
<input type="button" onclick="addRow()" value="Add" />
<input type="button" onclick="editRow()" value="Edit" />
<input type="button" onclick="delRow()" value="Delete" />
<trirand:jqgrid runat="server" ID="JQGrid1"
OnRowDeleting="JQGrid1_RowDeleting"
OnRowAdding="JQGrid1_RowAdding"
OnRowEditing="JQGrid1_RowEditing">
<Columns>
<trirand:JQGridColumn DataField="Addressbookid" Editable="false" PrimaryKey="true" />
<trirand:JQGridColumn DataField="ClientName" Editable="true" />
<trirand:JQGridColumn DataField="Clientno" Editable="true" />
<trirand:JQGridColumn DataField="IndustryName" Editable="true" />
</Columns>
<ToolBarSettings ShowEditButton="true" ShowAddButton="true" ShowDeleteButton="true" />
<EditDialogSettings CloseAfterEditing="true" Caption="The Edit Dialog" />
<AddDialogSettings CloseAfterAdding="true" />
</trirand:jqgrid>
</div>
<br /><br />
</div>
</form>
Here's the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestApp
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JQGrid1.DataSource = GetData();
JQGrid1.DataBind();
}
protected DataTable GetData()
{
if (Session["EditDialogData"] == null)
{
// Create a new Sql Connection and set connection string accordingly
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Sandbox"].ConnectionString;
sqlConnection.Open();
string sqlStatement = "Select * from voiceportal.dbo.clients_v";
// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlStatement, sqlConnection);
// Create a new DataTable
DataTable dtResult = new DataTable();
// Fill the DataTable with the result of the SQL statement
sqlDataAdapter.Fill(dtResult);
Session["EditDialogData"] = dtResult;
return dtResult;
}
else
{
return Session["EditDialogData"] as DataTable;
}
}
}
}
Any suggestions on how I can fix this?
Thanks
My two cents.
Make sure that the grid locale js file is in the right place and served well to your browser. See the related line:
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
Open up your developer console with F12, refresh the page and look for the downloaded files and error messages on the console which can tell if this doesn't go well.
Double check that the data you serve matches the column configuration. Pay special attention to camel casing. .NET properties start with uppercase, they are camel cased, but JSON data often starts with lowercase. That also depends on if you use any transformations (like NewtonSoft and stuff). I don't know what's in your voiceportal.dbo.clients_v table, please specify your schema. In your ASPX code Addressbookid and Clientno are not camel cased. Shouldn't they be AddressbookId and ClientNo? Depends on your schema and what actually comes through the wire.

How to Update the value of textbox in asp.net using c#?

I have this program in asp.net using C#
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="first" runat="server">
Text Boxes
<asp:TextBox ID="txtnr" runat="server"></asp:TextBox><br />
<asp:Button ID="btnxt1" runat="server" Text="Next" onclick="btnxt1_Click"/><br />
</div>
<div id="second" runat="server">
<asp:Table ID="tbl" runat="server"></asp:Table>
<asp:Button ID="btnx2" runat="server" Text="Next" onclick="btnx2_Click"/><br />
</div>
<div id="third" runat="server">
<asp:Label ID="lblxx" runat="server" Text=""></asp:Label><br />
</div>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
static int numr = 0;
static TableHeaderCell[] tc2;
static TextBox[] txtb;
protected void Page_Load(object sender, EventArgs e){}
protected void btnxt1_Click(object sender, EventArgs e)
{
numr = int.Parse(txtnr.Text);
TableHeaderRow tr;
tc2 = new TableHeaderCell[numr];
txtb = new TextBox[numr];
for (int i = 0; i < numr; i++)
{
tr = new TableHeaderRow();
tc2[i] = new TableHeaderCell();
txtb[i] = new TextBox();
txtb[i].Text = "w";
tc2[i].Controls.Add(txtb[i]);
tr.Controls.Add(tc2[i]);
tbl.Controls.Add(tr);
}
}
protected void btnx2_Click(object sender, EventArgs e)
{
for (int i = 0; i < numr; i++)
lblxx.Text += txtb[i].Text+"<br/>";
}
}
Program steps:
enter number of text-boxes to appear (say = 4) and click 'Next'
four text-boxes will appear (the program sets the value of textbox = "w",to understand the problem)
user can set other value for the text for the four text boxes (say: 1 , 2 , 3 , 4) then click next
finally, the program print the values of text boxes, but the problem is the program
will print: wwww not "1234" :( ??
How to fix this problem??
The problem is due to the fact that dynamic controls (like yours) do not automatically maintain their state after a post back and you should handle it on your own.
Please follow this link for a very similar question and then this link for the corresponding solution.

Asp.net Dropdownlist selected index changed AND TextChanged Events not Fire? (C#)

I am new to ASP>NET(C#). But I am using Winform before.
In my Project I have two dropdown list. if i change the one,.. the second will change auto.
But even event also not firing in ASP.net. Without event how to i manage that?.
<div id="Div1" class="ui-content ui-body-a" runat="server">
<asp:dropdownlist id="ddlOutlet" runat="server" autopostback="True" onselectedindexchanged="ddlOutlet_SelectedIndexChanged"
ontextchanged="ddlOutlet_TextChanged">
</asp:dropdownlist>
<br />
<asp:dropdownlist id="ddlServedAt" runat="server">
</asp:dropdownlist>
<br />
<asp:button id="btnLogin" runat="server" text="LogIn" />
</div>
C#
I already Added items in both dropdown list in page load event. But When I change the ddlOutlet selected index changed Event not firing. So I tried to TextChanged Events Also. But nothing happened. What is problem?.
Page Load Event -
protected void Page_Load(object sender, EventArgs e)
{
HelpingFunctions hp = new HelpingFunctions();
string id = Request.QueryString["id"];
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "SELECT c.Outlet_Master_Name,d.Fbserved_Served FROM mcs_user a, mcs_user_outlet b,outlet_master c,fb_served d WHERE a.Mcs_User_Id='" + id + "' and"
+ " a.Mcs_User_Id = b.Mcs_User_Outlet_User_Id and c.Outlet_Master_Id = b.Mcs_User_Outlet_Outlet_Id and c.Outlet_Master_Id=d.Fbserved_outletid";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlOutlet.Items.Add(Reader[0].ToString());
ddlServedAt.Items.Add(Reader[1].ToString());
}
connection.Close();
}
Selected Item -
protected void ddlOutlet_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlServedAt.SelectedItem.Value = Reader[0].ToString();
}
connection.Close();
}
I read some same issue problem solutions, but they told to set AutoPostBack="True". I checked that also.
I don't know why ASP.net hard to Event firing also?.
UPDATED QUESTION
In my Project,.. I am using jquerymobile(http://jquerymobile.com/) with ASP.Net and mysql.
I have two drop down list controls and ONE button.
But When I change the ddlOutlet selected index changed Event not firing. After the button Click the Events Are fired Correctly. But Before that They not fire. I do't know Why its happen.
I Give my Complete Code Below.
My Complete ASPX File :-
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OutLet.aspx.cs" Inherits="MobileApp.OutLet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta name="viewport" content="width=device-width; height=device-height; initial-scale=1.0; maximum-scale=1.5; user-scalable=no;" />
<link href="Styles/jquery.mobile-1.0b3.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.mobile-1.0b3.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server" data-ajax="false">
<div id="mainheader" class="ui-header-fixed ui-bar-a">
</div>
<div id="Div1" class="ui-content ui-body-a" runat="server">
<%-- <asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>--%>
<asp:DropDownList ID="ddlOutlet" runat="server"
AutoPostBack="True" onselectedindexchanged="ddlOutlet_SelectedIndexChanged"
ontextchanged="ddlOutlet_TextChanged">
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlServedAt" runat="server" AutoPostBack="True">
</asp:DropDownList>
<br />
<asp:Button ID="btnLogin" runat="server" Text="LogIn"
onclick="btnLogin_Click" />
<%-- </ContentTemplate>
</asp:UpdatePanel> --%>
</div>
</form>
</body>
</html>
my Code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace MobileApp
{
public partial class OutLet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HelpingFunctions hp = new HelpingFunctions();
string id = Request.QueryString["id"];
if (!Page.IsPostBack)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "SELECT c.Outlet_Master_Name,d.Fbserved_Served FROM mcs_user a, mcs_user_outlet b,outlet_master c,fb_served d WHERE a.Mcs_User_Id='" + id + "' and"
+ " a.Mcs_User_Id = b.Mcs_User_Outlet_User_Id and c.Outlet_Master_Id = b.Mcs_User_Outlet_Outlet_Id and c.Outlet_Master_Id=d.Fbserved_outletid";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlOutlet.Items.Add(Reader[0].ToString());
ddlServedAt.Items.Add(Reader[1].ToString());
}
connection.Close();
}
}
protected void ddlOutlet_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlServedAt.SelectedValue = Reader[0].ToString();
}
connection.Close();
}
protected void ddlOutlet_TextChanged(object sender, EventArgs e)
{
//MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
//string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
//MySqlCommand command = new MySqlCommand(query, connection);
//connection.Open();
//MySqlDataReader Reader = command.ExecuteReader();
//while (Reader.Read())
//{
// ddlServedAt.SelectedItem.Value = Reader[0].ToString();
//}
//connection.Close();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
}
}
}
Create the drop down list(the one that changes the content of the other one)
Activity: <asp:DropDownList ID="cmbActivity" runat="server" OnSelectedIndexChanged="cmbActivity_SelectedIndexChanged" AutoPostBack="true" />
Then in your C#, your load event should be like this
if (Session["staffId"] == null)
{
Response.Redirect("~/login.aspx");
}
else
{
if (!IsPostBack)
{
cmbActivity.DataSource = a;
cmbActivity.DataTextField = "activityName";
cmbActivity.DataValueField = "activiyId";
}
}
Your selectedIndex_Changed method still remains the same. This should work. Have more than one item in the list to be sure.
I hope this helps
try by Adding Page.IsPostBack in your page_Load event...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//your page load code.....
}
}
EDIT - 1
Sample Code of ASPX page in Web Application
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList id="id1" runat="server" AutoPostBack="true"
onselectedindexchanged="id1_SelectedIndexChanged">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="id2" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
Sample code of code behind in Web Application
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void id1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Sample code of ASPX page in Website
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList id="id1" runat="server" AutoPostBack="true"
onselectedindexchanged="id1_SelectedIndexChanged">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="id2" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
Sample code of Code behind in Website
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void id1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
OP already had this in his question, but I was missing autopostback="True"

Categories