[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# Can't refresh data after an Update

Posted on 2008-06-19
9
Medium Priority
?
1,253 Views
Last Modified: 2011-10-19
I'm tring to get my page to reflect the data change after a update from a button click.
The info only shows the updated data on window refresh.
how can I get my page to reflect the updated data?


Update page /////////////////////////////////////
 
Update data query  >>> (the code after)
dal.Refresh();
dal.LoadProjData1("id", taskid);
DataRow rsProj = dal.GetProjData1.Tables[0].Rows[0];
 
 
app_code\dal.cs \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
 
public static DataSet GetProjData1 = null;
    public static void LoadProjData1(string field, string value)
    {
        string connectionString = ConfigurationManager.ConnectionStrings["MyAccess"].ConnectionString;
        OleDbConnection dbConnection = new OleDbConnection(connectionString);
        string qry;
 
        if (field == "uid")
        {
            qry = "select * from proj where uid = " + value + " order by web_start desc";
        }
        else if (field == "id")
        {
            qry = "select * from proj where id = " + value + " order by web_start desc";
        }
        else
        {
            // Will not work without this else.
            qry = "";
        }
 
        OleDbCommand cmd = new OleDbCommand(qry, dbConnection);
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
 
        GetProjData1 = new DataSet();
        da.Fill(GetProjData1);
 
        //return GetProjData1;
    }
    public static void Refresh()
    {
        GetProjData1 = null;
    }

Open in new window

0
Comment
Question by:quest_capital
  • 5
  • 4
9 Comments
 
LVL 18

Expert Comment

by:Richard Lee
ID: 21824698
I'm assuming this is a windows forms application and you are binding the data to a control(s).

Try rebinding the DataRow in the Click event.

Please provide more info. if this does not help.
0
 

Author Comment

by:quest_capital
ID: 21825540
DaTribe:

I don't have a DataRow, the data is going to form fields like:
dd_status.Text = rsProj["status"].ToString();
No GridView.

The code below works fine but it is in the same page I just want to move the data connections to the Dal class out side the page.
my update page //////////////////////////
...
String qry = "Update proj set " + strdr + " where [id]=" + hf_id.Value;
 
        string connectionString = ConfigurationManager.ConnectionStrings["MyAccess"].ConnectionString;
        OleDbConnection dbConnection = new OleDbConnection(connectionString);
        dbConnection.Open();
        OleDbCommand cmd = new OleDbCommand(qry, dbConnection);
        cmd.ExecuteNonQuery();
        
        Label13.Text = "<em>Project Status Updated:</em> " + DateTime.Now.ToString("dd MMM yyyy hh:mm tt");
 
        //dal.UpdateProjData(qry);
 
        //dal.Refresh();
        //dal.LoadProjData1("id", taskid);
        //DataRow rsProj = dal.GetProjData1.Tables[0].Rows[0];
        
        cmd = new OleDbCommand("select * from proj where [id]=@taskid", dbConnection);
        cmd.Parameters.AddWithValue("@taskid", taskid);
 
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet("rsPCode");
        da.Fill(ds);
 
        DataRow rsProj = ds.Tables[0].Rows[0];
 
        dd_status.Text = rsProj["status"].ToString();
...

Open in new window

0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 21829146
Here is what you need to do:

1. Seperate your data access code and return DataRow / DataTable / String. However it would be much better if you create a structure to store the contents of the query and then return and instance of that structure.

2. On your UI, in the event that causes the application to check for new data you need to:
  a. Call the data access layer and acquire the returned data.
  b. Change the Text property of the control you wish to update.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SampleWinForm
{
	/// <summary>
	/// Maintains customer details
	/// </summary>
	public struct Customer
	{
		public int ID;
		public string FirstName;
		public string LastName;
	}
 
	/// <summary>
	/// Customer data access object
	/// </summary>
	public class CustomerDAO
	{
		public static Customer GetCustomer(int id)
		{
			// Do some data access
 
			// Create customer and set values
			Customer c = new Customer();
			//c.FirstName = 
 
			// Hand customer over to client
			return c;
		}
	}
}
 
 
-------> Client
 
 
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;
 
namespace SampleWinForm
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}
 
		private void btnUpdate_Click(object sender, EventArgs e)
		{
			int Id = 1;
 
			Customer c = CustomerDAO.GetCustomer(Id);
			CustomerName.Text = String.Format("{0}, {1}", c.FirstName, c.LastName);
		}
	}
}

Open in new window

0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 18

Expert Comment

by:Richard Lee
ID: 21829157
Here is the UI
SampleWinForm.jpg
0
 

Author Comment

by:quest_capital
ID: 21830958
DaTribe:

Dude you lost me..... I have a web application not Winforms.
0
 
LVL 18

Accepted Solution

by:
Richard Lee earned 2000 total points
ID: 21831374
Okay lets try again mate. What I am trying to show you here is how to separate your data access layer from your UI plus how to return a sensible object to your UI rather than a DataRow / DataTable / etc. Also how to get the result reflected on the UI when the button is clicked. (I'm assuiming you don't mind the page posting back when you clicked the button - If this is not the case then we will have to get into AJAX)

The first code sample show you how to seperate your data access layer from your UI and how to return a sensible structure which is more readable and abides by the principles of MURRE (maintainability, usability, reusability, reliability, extendability); there are more stuff to consider but I won't get into that now.

Please look at the comments so you know where to slot your code in. Remember your data access layer is only concerned with getting data from the datasource and returning it in a sensible fashion. Your client code / UI will worry about how it wants to use this data.

The second code sample shows the UI markup and code showing how to handle the button event. Let me know if this works otherwise send me your code and I can refactor it for you.
// 1st code sample
 
using System;
 
/// <summary>
/// Maintains customer details
/// </summary>
public struct Customer
{
	public int ID;
	public string FirstName;
	public string LastName;
}
 
/// <summary>
/// Customer data access object
/// </summary>
public class CustomerDAO
{
	public static Customer GetCustomer(int id)
	{
		// Do some data access
 
		// Create customer and set values
		Customer c = new Customer();
 
		// Sample data
		c.FirstName = "FN " + DateTime.Now.ToLongTimeString();
		c.LastName = "LN " + DateTime.Now.ToLongDateString();
 
		// Hand customer over to client
		return c;
	}
}
 
 
// 2nd code sample
 
<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
		<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
		<br /><br />
		<asp:Button ID="btnUpdate" runat="server" Text="Update" 
			onclick="btnUpdate_Click" />
    </div>
    </form>
</body>
</html>
 
 
using System;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
	protected void btnUpdate_Click(object sender, EventArgs e)
	{
		Customer c = CustomerDAO.GetCustomer(1);
		Label1.Text = String.Format("{0}, {1}", c.FirstName, c.LastName);
	}
}

Open in new window

Untitled.jpg
0
 

Author Comment

by:quest_capital
ID: 21833226
DaTribe:

Thx for your time spent on this issue.
I created a small 2 page example of what I'm tring to acheive.
In the code below I hav both the SELECT and UPDATE methods in app_code\exp1_dal.cs
and the UI in exp1.aspx I want the Label2 to be updated after I change the data in the textboxes and click the button.

Can you modify this exmple with this data provided below.
exp1_dal ////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
 
public class exp1_dal
{
	public exp1_dal()
	{
 
	}
 
    public static string AccessCnn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Inetpub\\wwwroot\\mydesktop\\projects.mdb";
 
    public static DataSet GetMemData(string uid)
    {
        string connectionString = AccessCnn;
        OleDbConnection dbConnection = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand("select * from userinfo where uid = @uid", dbConnection);
        cmd.Parameters.AddWithValue("@uid", uid);
 
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
 
        return ds;
    }
 
    public static DataSet UpdateMemData(string qry)
    {
        string connectionString = AccessCnn;
        OleDbConnection dbConnection = new OleDbConnection(connectionString);
        dbConnection.Open();
        OleDbCommand cmd = new OleDbCommand(qry, dbConnection); 
        cmd.ExecuteNonQuery();
        return GetMemData("125794");
    }
}
/////////////////////////////////////////////////////////////
 
exp1.aspx.cs /////////////////////////////////////////////////
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
public partial class mydesktop_exp1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string uid = "125794";
        DataRow rsMemData = exp1_dal.GetMemData(uid).Tables[0].Rows[0];
 
        if (!IsPostBack)
        {
            
 
            tb_fname.Text = rsMemData["fname"].ToString();
            tb_lname.Text = rsMemData["lname"].ToString();
            
        }
        Label2.Text = rsMemData["fname"].ToString() + " " + rsMemData["lname"].ToString();
 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string qry = "update userinfo set fname = '" + tb_fname.Text + "', lname = '" + tb_lname.Text + "' where uid = '125794'";
        exp1_dal.UpdateMemData(qry);
        Label1.Text = "Data updated.";
    }
}
//////////////////////////////////////////////////////////////

Open in new window

0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 21837087
You can download the revised code here: http://www.avantprime.com/Profile/Richard/Samples/EE-ID23499635-Website.zip

I have refactored and the code should be much easier to use and much more maintainable. Som performance improvements have been made. Notably the update method.

Hope this helps!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month19 days, 5 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question