Why ComboBox items need to be reselected to obtain Value? - asp.net

I am using ext.net 1.3 controls in my ASP.NET 4.0 application. I have several ComboBox controls on my Web Form. The page is supposed to perform two tasks, Insert and Update. There are no issues when a new record is saved, but when I try to fill the ComboBox controls with an existing database values, various issues pop up. The most troubling is this one:
The ComboBox displays the Text from the database, but it neither gets populated nor I am able to pick the ComboBox Value Member. This is because it is not populated. I have written code to populate ComboBox in the Page Load event.
I am using this code to pick a value from the database and show it on the ComboBox:
string Query = "SELECT CustName FROM CustomerMaster WHERE CustID = " + Session["CustomerID"];
var result = DB.Single<Customer>(Query);
CustomerComboBox.setValue = result.CustName;
This code successfully retrieves the Customer Name and displays in the ComboBox. What it is not doing is that it is not selecting from the ComboBox Item List and neither populating the ComboBox.
If I try to retrieve the Value Member of the Text using:
CustomerComboBox.SelectedItem.Value;
it gives error.
To make it work, I need to click on the ComboBox again to make it populate and than I manually select the same customer name from the list to pick the value.
How to get rid of this issue?
-- Edited --
The code to fill ext.net ComboBox is this:
public void FillExtComboList(string ParameterFlag, ComboBox DropDownName)
{
string Query = "";
using (TransactionScope transactionScope = new TransactionScope())
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cncustomer"].ConnectionString.ToString()))
{
con.Open();
SqlDataReader dr;
try
{
if (ParameterFlag == "Customer")
{
Query = "SELECT CustName FROM CustomerMaster";
}
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Text = dr[0].ToString();
DropDownName.Items.Add(extLI);
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
con.Close();
// RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
}
} /* End of SQL Connection */
transactionScope.Complete();
} /* End of Transaction Scope */
}
On Page Load event, the ComboBox control is filled with above method.

I don't see an instruction to fill the combo box, only to set its selected value. Arent you missing a CustomerComboBox.DataSource = someList or something like that?
<-- EDIT -->
Sorry, I thought the setValue was the code on your page load...
OK, this is not be the answer to your problem, but an important performance fix.
you should do this when loading the combo:
when executing the SQL Query:
Query = "SELECT CustID, CustName FROM CustomerMaster"
when filling the combo:
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Value = dr["CustId"].ToString();
extLI.Text = dr["CustName"].ToString();
DropDownName.Items.Add(extLI);
so when you want to select an item, you just do this:
CustomerComboBox.setValue = Session["CustomerID"];
and avoid going back to the database to get the customer name.
Now, could you share the code you have to handle the combobox click? Since it does fill the combo, it may throw some ligth to us. Also, try adding
CustomerComboBox.DataBind()
And, come to think of it, I see on Page_Load you use "DropDownName" and later on you use "CustomerComboBox". Could that be the problem?

If I understand you correctly try this code:
protected void Page_Load(object sender, EventArgs e) {
FillExtComboList(DropDownName);
// Set value that you want
DropDownName.SetValueAndFireSelect("Test 3");
}
public void FillExtComboList(ComboBox DropDownName) {
try {
//Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
for (int i = 0; i < 10; i++) {
Ext.Net.ListItem extLI = new Ext.Net.ListItem();
extLI.Text = "Test " + i;
DropDownName.Items.Add(extLI);
}
} catch (Exception ex) {
// RunCustomScript("alert('" + ex.Message.ToString() + "')", callingPageObjectName);
} /* End of Transaction Scope */
}

Related

Check at run time if primary key exists

I am working in asp.net. I have a textbox named formidtxt and another textbox is colortxt. Now what I want is that when a user enters an Form ID in formidtxt then at the same time it should start checking whether there already exists a form id with same ID that has been entered and if Form ID already exists in database then the color of colortxt textbox should change to red else it should be green.
I have an idea that it can be done by using events in text boxes but can't understand the working. My database is in SQL Server 2008.
Try this C# code;
private void Page_Load(object sender, EventArgs e)
{
// formidtxt is the name of the textbox
this.formidtxt.TextChanged += FormIDTextBox_TextChanged;
formidtxt.AutoPostBack = true;
}
Note that this method was written inside the Page_Load method.
TextChanged is an event and it occurs when the text is modified in a TextBox.
In this case, when the formidtxt (textbox) text changes, it will call the FormIDTextBox_TextChanged method.
private void FormIDTextBox_TextChanged(object sender, EventArgs e)
{
int x = 0;
// convert textbox text (string) to int
Int32.TryParse(formidtxt.Text, out x);
// call IsIDAvailableDAO method
// x is the converted int value
if (IsIDAvailableDAO(x))
{
colortxt.BackColor = System.Drawing.Color.Red;
}
else
{
colortxt.BackColor = System.Drawing.Color.Green;
}
}
This method will get the text from the textbox (formidtxt) and send it to the IsIDAvailableDAO method as a parameter.
Using the IsIDAvailableDAO method, we can check whether the ID is available in the database or not. If it is available, then the method will return a TRUE boolean value. If not, it will return a False boolean value.
According to that boolean value, you can change the color of the colortxt textbox as you want or do something else.
private Boolean IsIDAvailableDAO(int id)
{
Boolean output;
using (SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Testing;Integrated Security=True"))
{
string query = #"SELECT CASE WHEN COUNT(ID) >= 1 THEN CAST( 1 as BIT ) ELSE CAST( 0 as BIT )
END As IsAvailable
FROM TableName
WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(query, myConnection);
cmd.Parameters.AddWithValue("#ID", id);
myConnection.Open();
output = (Boolean)cmd.ExecuteScalar();
myConnection.Close();
}
return output;
}
In this method (IsIDAvailableDAO), Please change the query (TableName, ID, etc.) and connectionstring as appropriate.
You also has to add this namespace: using System.Data.SqlClient;
https://www.connectionstrings.com/sql-server-2008/
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces

ASP.NET Cache always returns null

I am using SQLCacheDependency in my ASP.NET application with Query Notifications.
I followed this article to set up my database with success.However whenever I am trying to store data in the cache object.It just does not hold value.It is always null .I am not getting any errors or exceptions.
Here is my code
Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Data.SqlClient.SqlDependency.
Start(ConfigurationManager.ConnectionStrings["McdConn"].ToString());
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
System.Data.SqlClient.SqlDependency.
Stop(ConfigurationManager.ConnectionStrings["McdConn"].ToString());
}
public static class CacheManagement
{
public static DataTable CreateCache(string cacheName, string tableName, string query)
{
DataTable dtResult = new DataTable();
try
{
string connectionString = ConfigurationManager.ConnectionStrings["McdConn"].ToString();
dtResult = HttpContext.Current.Cache[cacheName] as DataTable;
if (dtResult == null)
{
dtResult = new DataTable();
using (var cn = new SqlConnection(connectionString))
{
cn.Open();
var cmd = new SqlCommand(query, cn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlCacheDependencyAdmin.EnableNotifications(connectionString);
if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connectionString).Contains(tableName))
{
SqlCacheDependencyAdmin.EnableTableForNotifications(connectionString,tableName);
}
var dependency = new SqlCacheDependency(cmd);
//SqlDataAdapter ad = new SqlDataAdapter(cmd);
//ad.Fill(dsResult);
SqlDataReader reader = cmd.ExecuteReader();
dtResult.Load(reader);
HttpContext.Current.Cache.Insert(cacheName, dtResult, dependency);
}
}
}
catch (Exception ex)
{
Exception_Log.ExceptionMethod("Web", "CacheManagement.cs", "CacheManagement", ex);
}
return dtResult = HttpContext.Current.Cache[cacheName] as DataTable;
}
}
Code Behind
var dtCachedCategories = HttpContext.Current.Cache["tbl_CategoryMaster_Cached"] as DataTable;
if (dtCachedCategories == null)
{
dtCachedCategories = CacheManagement.CreateCache("tbl_CategoryMaster_Cached","dbo.tbl_CategoryMaster_Languages", "Select * from dbo.tbl_CategoryMaster_Languages");
}
The above always returns null.
Can anyone help me in pointing out what could be missing?
Well there's a lot you can do to debug your code and arrive at a conclusion. It seems like your cached item is getting removed too frequently.
1.) Use CacheItemPriority.NotRemovable to Cache.Insert() to make sure ASP.NET doesn't removes
your item whenever it feels so. use the Insert() method explained here. Check this MSDN
article too.
2.) To find out the reason why your cached item is getting removed , log this removal action using
CacheItemRemovedCallback delegate option of your Cache.Insert() method. Check this Insert method
overload version and also this link.
3.) Make sure your dtresult as well as your reader is not null. Check the lines:
SqlDataReader reader = cmd.ExecuteReader(); & dtResult.Load(reader); , together with your logs.
4.) Check your application Pool recycle time. This link has everything related to App pool settings ( IIS 7 +).
5.) This link has a solution for App pool of IIS 6: http://bytes.com/topic/net/answers/717129-c-asp-net-page-cache-getting-removed-too-soon
Also, try using HttpRuntime.Cache method to see if it works.
System.Web.HttpRuntime.Cache.Insert(cacheName, dtResult, dependency);

My update query doesn't work on database

I wrote this code in my login page. My code doesn't any error but update query doesn't apply on my database.
Fist query works and I redirect to index.aspx but update query (second query) doesn't apply!!!!
protected void btnLogin_Click(object sender, EventArgs e)
{
Database db1 = new Database();
string query = "select * from Admins where UserName=#username and cast(Password as varbinary)=cast(#password as varbinary)";
SqlCommand smd = new SqlCommand(query, db1.sc);
smd.Parameters.AddWithValue("#username", txtUsername.Text);
smd.Parameters.AddWithValue("#password", General.CreatePasswordHash(txtPassword.Text));
SqlDataReader sdr = smd.ExecuteReader();
smd.Parameters.Clear();
if (sdr.Read())
{
Session.Add("username", sdr[0].ToString());
string nowEnter = sdr[5].ToString();
query = "update Admins set LastEnter=#lastEnter, NowEnter=#nowEnter where UserName=#username";
string now = General.getPersianDateNow() + " ساعت " + General.getPersianTimeNow();
smd.CommandText = query;
smd.Parameters.AddWithValue("#lastEnter", nowEnter);
smd.Parameters.AddWithValue("#nowEnter", now);
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
sdr.Close();
smd.ExecuteNonQuery();
Response.Redirect("~/admin/Index.aspx", false);
}
else
{
lblError.Visible = true;
}
}
In my opinion the problem is with index of sdr. First one you invoke
Session.Add("username", sdr[0].ToString());
Two lines below you use
smd.Parameters.AddWithValue("#username", sdr[1].ToString());
Anyway the safest way is to create select statement with named colums instead of using *
Check that the value you are using for the username exists in the table.
You're also adding the same parameter twice. I don't know how the SqlCommand class will handle that and I can't test it right now, but I think it might be a good idea to clear your parameters (smd.Parameters.Clear()) between executions.

Data not being written to Database ASP.Net

I am building a Forum in ASP.Net but have a small problem.
I have 1 user who creates a topic and can write a post to it fine, but if another user logs in, it won't insert the post into the database. It's returning that it does but nothing inserts. The original user can login and still post but no-one else can.
this is my code in behind
protected void addPostBtn_Click(object sender, EventArgs e)
{
//Define ADO.NET objects.
string insertSQL;
string topic = Request.QueryString["topicid"].ToString();
insertSQL = "INSERT INTO Posts (TopicID, PostBody, PUserID)"
+ "VALUES (#Topic, #NewPostText, #PUserID)";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
// Try to open the database and execute the update
int added = 0;
try
{
cmd.Parameters.AddWithValue("#Topic", topic);
cmd.Parameters.AddWithValue("#NewPostText", newPostText.InnerText);
cmd.Parameters.AddWithValue("#PUserID", Session["User_ID"]);
con.Open();
added = cmd.ExecuteNonQuery();
lblResults.Text = "Your post has been added";
}
catch (Exception err)
{
lblResults.Text = "Error inserting record. " + err.Message;
}
finally
{
con.Close();
}
if (added > 0)
{
this.BindRepeater();
}
}
I don't get any errors at all. It says it submitted fine, but it's not in the database unless the original poster does it.
EDIT:
Just realized it's to do with my view. This is my current view that it's reading from
SELECT dbo.Posts.PostBody, dbo.Posts.PostDate, dbo.Posts.PostID, dbo.[User].username, dbo.Topic.TopicID
FROM dbo.Topic RIGHT OUTER JOIN
dbo.Posts ON dbo.Topic.TopicID = dbo.Posts.TopicID LEFT OUTER JOIN
dbo.[User] ON dbo.Topic.TUserID = dbo.[User].UserID AND dbo.Posts.PUserID = dbo.[User].UserID
But it's returning NULL now for the other users names
The view needs to be as follows
SELECT dbo.Posts.PostBody, dbo.Posts.PostDate, dbo.Posts.PostID, dbo.[User].username, dbo.Topic.TopicID
FROM dbo.Topic LEFT OUTER JOIN
dbo.Posts ON dbo.Topic.TopicID = dbo.Posts.TopicID LEFT OUTER JOIN
dbo.[User] ON dbo.Posts.PUserID = dbo.[User].UserID

Enabling view state is not working with controls in web part

What I have?
I have a simple web part which has a Table. The table has two controls, a TextBox and a Button. In CreateChildControls() method, I add the controls to table if !Page.IsPostBack is true. And, table has view state enabled.
What I want to do?
I want the controls in the table to be present after the post back.
What problem am I facing?
I except the the controls, TextBox and Button to be present in the table after the post back. But it is not happening.
I feel building the whole table in every post back is little costly and enabling view state will solve this problem.
Can anyone tell if I am missing something?
Thanks in advance!
Update:
I tried setting EnbleViewState property of web part. Still the same result.
Code:
public class TreeWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
private Table table;
private Button clickMe;
private TextBox content;
protected override void CreateChildControls()
{
base.CreateChildControls();
BuildTable();
}
private void BuildTable()
{
table = new Table();
clickMe = new Button();
content = new TextBox();
table.ID = "myTable";
table.EnableViewState = true;
if (!this.Page.IsPostBack)
{
clickMe.Text = "Click Me!";
clickMe.Click += new EventHandler(clickMe_Click);
content.Text = "Click button to set text";
content.Width = Unit.Pixel(200);
TableCell cell = new TableCell();
cell.Controls.Add(content);
TableRow tr = new TableRow();
tr.Cells.Add(cell);
table.Rows.Add(tr);
cell = new TableCell();
cell.Controls.Add(clickMe);
tr = new TableRow();
tr.Cells.Add(cell);
table.Rows.Add(tr);
}
this.Controls.Add(table);
}
protected void clickMe_Click(object sender, EventArgs e)
{
content.Text = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
}
}
Since the view state only persists changed control state across postbacks, and not the actual controls themselves, dynamically added controls must be added to the ASP.NET Web page, on both the initial visit as well as all subsequent postbacks. For more information visit Here.

Resources