ถามเรื่องการส่งค่าข้าม page ครับ...ตอนนี้ใช้ C#.net อยุ่ครับ จะถามเรื่อง การส่งค่าข้าม page
ที่ gridview ต้องกำหนด datakeyname
ตอนอีเว็นต์ rowupdate ให้ redirect ไปหน้า edit พร้อมส่ง key value ผ่านทาง method get
ที่หน้า edit ก็เอา key value ไป query ข้อมูลมา bind ให้ textbox
ปล. ตัวอย่าง gridview เพียบลองหาดูด้านล่าง
Date :
2010-06-25 08:50:19
By :
tungman
งงอะครับ - -* นี่ code ผมอะครับ
Code (C#)WebForm3.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="Test.WebForm3" %>
<!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:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Sur" HeaderText="Sur" SortExpression="Sur" />
<asp:CommandField HeaderText="Sel/Edi/Del" ShowDeleteButton="True"
ShowEditButton="True" ShowSelectButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="la1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="la2" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="la3" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="dele" runat="server" onclick="dele_Click" Text="Delete" />
<br />
<asp:Button ID="edit" runat="server" onclick="edit_Click" Text="Edit" />
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString %>"
SelectCommand="SELECT * FROM [Test]"></asp:SqlDataSource>
</form>
</body>
</html>
Date :
2010-06-25 22:06:48
By :
recoilza
Code (C#)WebForm3.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.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace Test
{
public partial class WebForm3 : System.Web.UI.Page
{
string sqlConn = WebConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection();
SqlCommand sqlcom = new SqlCommand();
SqlDataAdapter da;
DataSet ds;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
la1.Text = row.Cells[0].Text;
la2.Text = row.Cells[1].Text;
la3.Text = row.Cells[2].Text;
}
protected void dele_Click(object sender, EventArgs e)
{
//if (la1.Text == "1")
//{
// Response.Write("Please choose member for delete!!!");
//}
//else
//{
if (la1.Text != "")
{
int del = Convert.ToInt32(la1.Text);
Conn.ConnectionString = sqlConn;
Conn.Open();
string SqlDelMember = "DELETE FROM Test WHERE ID = " + del + "";
sqlcom.CommandType = CommandType.Text;
sqlcom.CommandText = SqlDelMember;
sqlcom.Connection = Conn;
sqlcom.ExecuteNonQuery();
Conn.Close();
Response.Redirect("~/WebForm3.aspx");
}
//}
}
protected void edit_Click(object sender, EventArgs e)
{
Session["ID"] = la1.Text;
Session["Name"] = la2.Text;
Session["Sur"] = la3.Text;
Response.Redirect("~/WebForm5.aspx");
}
}
}
Date :
2010-06-25 22:08:31
By :
recoilza
หน้านี้ คือ หน้าที่ รับค่าจาก WebForm3 มาน่ะครับ
หรือหน้าที่จะ Edit น่ะครับ TT^TT
Code (C#)WebForm5.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.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace Test
{
public partial class WebForm5 : System.Web.UI.Page
{
string sqlConn = WebConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection();
SqlCommand sqlcom = new SqlCommand();
SqlDataAdapter da;
DataSet ds;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
String id = (string)Session["ID"];
txt1.Text = id;
String name = (string)Session["Name"];
txt2.Text = name;
String Sur = (string)Session["Sur"];
txt3.Text = Sur;
// tx1.Text = txt1.Text;
}
protected void bt1_Click(object sender, EventArgs e)
{
Conn.ConnectionString = sqlConn;
Conn.Open();
string SqlChgStatus = "UPDATE Test SET Name = '" + txt2.Text + "', Sur = '" + txt3.Text + "' WHERE ID = " + txt1.Text + "";
sqlcom.CommandType = CommandType.Text;
sqlcom.CommandText = SqlChgStatus;
sqlcom.Connection = Conn;
sqlcom.ExecuteNonQuery();
Conn.Close();
Response.Redirect("~/WebForm3.aspx");
}
}
}
Date :
2010-06-25 22:09:54
By :
recoilza
ไม่เห็นจะน่างงตรงไหนเลย
======= เอา GridviewData.cs ไปไว้ใน folder app_code =====
GridviewData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
/// <summary>
/// Summary description for GridviewData
/// </summary>
public class GridviewData
{
SqlConnection sqlConnection;
public GridviewData()
{
//
// TODO: Add constructor logic here
//
string sqlConnectionString = WebConfigurationManager.ConnectionStrings["ProjectConnectionString"].ConnectionString;
sqlConnection = new SqlConnection(sqlConnectionString);
if (!TableExist())
CreateTable();
}
public DataTable GetAllData()
{
string sqlCommandString = "Select [ID], [Name], [SurName] From [Tungman]";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
DataTable Dt = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = sqlCommand;
dataAdapter.Fill(Dt);
return Dt;
}
public DataTable GetData(int ID)
{
string sqlCommandString = "Select [ID], [Name], [SurName] From [Tungman] Where [ID]=@ID";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlCommand.Parameters.AddWithValue("@ID", ID);
DataTable Dt = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = sqlCommand;
dataAdapter.Fill(Dt);
return Dt;
}
public void AddData()
{
string sqlCommandString = "Insert Into [Tungman] ([Name], [SurName]) Values (@Name, @SurName)";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlCommand.Parameters.AddWithValue("@Name", "AddNew");
sqlCommand.Parameters.AddWithValue("@SurName", "www.thaicreate.com");
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
public void UpdateData(int ID, string Name, string SurName)
{
string sqlCommandString = "Update [Tungman] Set [Name]=@Name, [SurName]=@SurName Where [ID]=@ID";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlCommand.Parameters.AddWithValue("@Name", Name);
sqlCommand.Parameters.AddWithValue("@SurName", SurName);
sqlCommand.Parameters.AddWithValue("@ID", ID);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
public void DeleteData(int ID)
{
string sqlCommandString = "Delete From [Tungman] Where [ID]=@ID";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlCommand.Parameters.AddWithValue("@ID", ID);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
private bool TableExist()
{
string sqlCommandString = "If Object_ID('Tungman', 'U') Is Not Null Select 'true' Else Select 'false'";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlConnection.Open();
bool haveTable = Convert.ToBoolean(sqlCommand.ExecuteScalar());
sqlConnection.Close();
return haveTable;
}
private void CreateTable()
{
string sqlCommandString = "Create Table [Tungman] ([ID] int Identity(1,1) Primary Key Clustered, [Name] nvarchar(50), [SurName] nvarchar(50))";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
FillData();
}
private void FillData()
{
DataTable Dt = new DataTable();
Dt.Columns.Add(new DataColumn("Name", typeof(string)));
Dt.Columns.Add(new DataColumn("SurName", typeof(string)));
for (int i = 0; i < 10; i++)
{
DataRow Dr = Dt.NewRow();
Dr["Name"] = string.Format("Tungman{0}", (i + 1).ToString());
Dr["SurName"] = "www.thaicreate.com";
Dt.Rows.Add(Dr);
}
string sqlCommandString = "Insert Into [Tungman] ([Name], [SurName]) Values (@Name, @SurName)";
SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
sqlCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
sqlCommand.Parameters.Add("@SurName", SqlDbType.NVarChar, 50, "SurName");
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.InsertCommand = sqlCommand;
dataAdapter.Update(Dt);
}
}
======= ส่วนพวกนี้วางไว้ที่ root =======
GridviewDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewDemo.aspx.cs" Inherits="GridviewDemo" EnableEventValidation="false" %>
<!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:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AddButton" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="DeleteButton" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" ForeColor="#333333" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="AddButton" runat="server" Text="Add" />
<asp:Button ID="EditButton" runat="server" Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" />
</div>
</form>
</body>
</html>
GridviewDemo.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class GridviewDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridviewData data = new GridviewData();
GridView1.DataSource = data.GetAllData();
GridView1.DataKeyNames = new string[] { "ID" };
GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
GridView1.SelectedIndexChanged += new EventHandler(GridView1_SelectedIndexChanged);
GridView1.DataBind();
AddButton.Click += new EventHandler(AddButton_Click);
EditButton.Click += new EventHandler(EditButton_Click);
DeleteButton.Click += new EventHandler(DeleteButton_Click);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference((GridView)sender, string.Format("Select${0}", e.Row.RowIndex.ToString())));
e.Row.Attributes.Add("onmouseover", "javascript:this.style.backgroundColor='#EFF3FB'; this.style.cursor='pointer'");
e.Row.Attributes.Add("onmouseout", "javascript:this.style.backgroundColor='#FFFFFF';");
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.SelectedRow.Attributes.Clear();
}
protected void AddButton_Click(object sender, EventArgs e)
{
GridviewData data = new GridviewData();
data.AddData();
GridView1.SelectedIndex = -1;
GridView1.DataSource = data.GetAllData();
GridView1.DataBind();
}
protected void EditButton_Click(object sender, EventArgs e)
{
if (GridView1.SelectedIndex > 0)
Response.Redirect(string.Format("~/GridviewEdit.aspx?id={0}", GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString()));
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
if (GridView1.SelectedIndex > 0)
{
GridviewData data = new GridviewData();
data.DeleteData(int.Parse(GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString()));
GridView1.SelectedIndex = -1;
GridView1.DataSource = data.GetAllData();
GridView1.DataBind();
}
}
}
GridviewEdit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewEdit.aspx.cs" Inherits="GridviewEdit" %>
<!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:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
<asp:TextBox ID="NameTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="NameTextBox"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="Label2" runat="server" Text="SurName: "></asp:Label>
<asp:TextBox ID="SurNameTextBox" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="SurNameTextBox"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="SaveButton" runat="server" Text="Save" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</div>
</form>
</body>
</html>
GridviewEdit.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class GridviewEdit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
GridviewData data = new GridviewData();
DataRow Dr = data.GetData(int.Parse(Request.QueryString["id"].ToString())).Rows[0];
if (!IsPostBack)
{
NameTextBox.Text = Dr["Name"].ToString();
SurNameTextBox.Text = Dr["SurName"].ToString();
}
}
else
{
SaveButton.Enabled = false;
}
SaveButton.Click += new EventHandler(SaveButton_Click);
CancelButton.OnClientClick = "javascript:history.go(-1); return false;";
}
protected void SaveButton_Click(object sender, EventArgs e)
{
GridviewData data = new GridviewData();
data.UpdateData(int.Parse(Request.QueryString["id"].ToString()), NameTextBox.Text, SurNameTextBox.Text);
Response.Redirect("~/GridviewDemo.aspx");
}
}
Date :
2010-06-26 01:22:50
By :
tungman
แล้วถ้าจะให้แสดงเฉพาะ..USER ที่ล็ิิอกอิงล่ะค่ะ (USER ID เป็นตัวแปรรับค่าจาก SESSION มาเก็บไว้)
จะต้องทำการกรอบข้อมูลก่อนจะแสดงตรงใหนค่ะ
Date :
2010-07-23 10:00:34
By :
ศรินญา
*กรอง
Date :
2010-07-23 10:01:27
By :
ต่อ
รบกวนถามหน่อยค่ะ พี่ tung man สุดหล่อ
คือว่าหนูได้ทำตาม โค้ดข้างบนแล้วอ่ะค่ะ แล้วที่นี้พอเอาหน้าฟอร์มเหมือนตัวอย่างด้านบน มาใส่ในหน้า master page พอกดปุ่ม Edit แล้ว
มันอยู่หน้าเดิมค่ะ ไม่ยอมไปหน้าที่กำหนดไว้ ไม่ทราบว่าเกิดจากปัญหาอะไรค่ะ .....ซึ่งก่อนหน้านี้ ถ้าไม่ใส่ในหน้า master page ยังทำได้ค่ะ
Date :
2010-07-30 09:53:53
By :
pucca
ajax script ไม่ทำงานครับ แก้ด้วย
ใน master page มี ScriptManager หรือเปล่า (ต้องมีด้วย)
ส่วนใน content page ให้ใช้ ScriptManagerProxy
Date :
2010-07-30 09:58:11
By :
tungman
ขอบคุณมากๆๆค่ะ
Date :
2010-07-30 10:13:21
By :
pucca
Load balance : Server 05