Solved

C# Can't refresh data after an Update

Posted on 2008-06-19
9
1,241 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
 
LVL 18

Expert Comment

by:Richard Lee
ID: 21829157
Here is the UI
SampleWinForm.jpg
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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 500 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
 

Author Closing Comment

by:quest_capital
ID: 31468881
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now