|
|
|
ต้องการย้ายข้อมูลจากGridview1ไปGridview2โดยใช้Checkbox |
|
|
|
|
|
|
|
ให้ใช้ DataTable ช่วยจะทำให้ง่ายขึ้น
ย้ายข้อมูลให้ย้ายที่ DataTable แล้วใช้ GridView แค่แสดงผลอย่างเดียวพอ
|
|
|
|
|
Date :
2010-03-26 12:11:38 |
By :
tungman |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ขอโด้คหน่อยจิ
ได้โปรด
|
|
|
|
|
Date :
2010-03-26 12:25:10 |
By :
sonmy |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ไม่ให้ ทำเอง
|
|
|
|
|
Date :
2010-03-26 12:42:35 |
By :
tungman |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
พี่ตึ๋งใจร้าย มากถึงมากที่สุดอ่า
|
|
|
|
|
Date :
2010-03-26 13:01:46 |
By :
blurEye |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ทำไมเป็นอ่ะดิ ถึงไม่ให้โค้ดอ่ะ
ถ้าเขียนเป็นแล้วจะเข้ามาตั้งกระทู้ทำไมอ่ะ
ถ้าไม่ช่วยอย่ามาก่อกวนได่ป่ะ
คนกำลังเครียดๆ
|
|
|
|
|
Date :
2010-03-26 13:12:24 |
By :
sonmy |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
อ้าว ขอโทษค่ะที่รบกวน
|
|
|
|
|
Date :
2010-03-26 13:25:25 |
By :
blurEye |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ไม่ได้ว่าคุณนะคับคุณStupid girl
ผมว่าไอ้คนข้างบนอ่ะครับ
|
|
|
|
|
Date :
2010-03-26 14:08:06 |
By :
sonmy |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
นี่หรือคนขอความช่วยเหลือ
เขียน c# ให้จะโดนด่าอีกไหม
TestGridView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestGridView.aspx.cs" Inherits="TestGridView" %>
<!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>
<script type="text/javascript">
function pageLoad() {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td valign="top">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</td>
<td valign="middle">
<asp:Button ID="Button1" runat="server" Text=">>" />
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="<<" />
</td>
<td valign="top">
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
TestGridView.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 TestGridView : System.Web.UI.Page
{
DataTable DataTable1;
DataTable DataTable2;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable1 = new DataTable();
DataTable2 = new DataTable();
SqlDatabaseManager Sql1 = new SqlDatabaseManager();
Sql1.CommandString = "Select * From [Global_UserClass]";
DataTable1 = Sql1.ExecuteQuery();
DataTable2 = DataTable1.Clone();
CheckBox CheckBox1 = new CheckBox();
TemplateBuilder TemplateBuilder1 = new TemplateBuilder();
TemplateField TemplateField1 = new TemplateField();
TemplateField1.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "CheckBox");
GridView1.Columns.Add(TemplateField1);
GridView1.DataSource = DataTable1;
GridView1.DataBind();
GridView2.DataSource = DataTable2;
GridView2.DataBind();
}
Button1.Click += new EventHandler(Button1_Click);
Button1.Click += new EventHandler(Button1_Click);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
}
}
// Here is the code for building the template field
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
public GridViewTemplate(DataControlRowType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
CheckBox checkAll = new CheckBox();
//checkAll.Attributes.Add("onclick", "javascript:checkAll(this.form);");
container.Controls.Add(checkAll);
break;
case DataControlRowType.DataRow:
CheckBox cb = new CheckBox();
cb.Text = "";
//cb.Attributes.Add("onclick", "javascript:colorRow(this);");
container.Controls.Add(cb);
break;
default:
break;
}
}
}
เอาไปครึ่งเดียวพอ โทษฐานปากดี ที่เหลือทำเอง 555+
|
|
|
|
|
Date :
2010-03-26 17:26:34 |
By :
tungman |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SqlDatabaseManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Configuration;
#region ========== Class SqlDatabaseManager ==========
/// <summary>
/// Summary description for SqlDatabase
/// </summary>
public class SqlDatabaseManager
{
#region ========== Global Variables ==========
private SqlConnection sqlConnection;
private SqlCommand sqlCommand;
private SqlTransaction sqlTransaction;
private List<string> errorCommand;
private string sqlConnectionString = string.Empty;
private string sqlConnectionKeyName = string.Empty;
private string sqlCommandString = string.Empty;
private string commandMessage = "You must execute command.";
private bool commandSuccess = false;
private bool transaction = false;
private int rowsAffected = 0;
#endregion
#region ========= Constructor ==========
/// <summary>
/// Use sql connection string from web.config configulation.
/// </summary>
public SqlDatabaseManager()
{
if (WebConfigurationManager.ConnectionStrings["SqlConnectionString"] != null)
{
//สำหรับ web.config ที่มีการ add connection string ชื่อ SqlConnectionString เอาไว้
//
//ตัวอย่างใน web.config
//<connectionStrings>
// <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SqlDatabase;Integrated Security=True;" providerName="System.Data.SqlClient"/>
//</connectionStrings>
sqlConnectionKeyName = "SqlConnectionString";
sqlConnectionString = WebConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
else
{
sqlConnection = new SqlConnection();
}
}
/// <summary>
/// Use sql connection string from web.config configulation by key name.
/// </summary>
public SqlDatabaseManager(string SqlConnectionKeyName)
{
sqlConnectionKeyName = SqlConnectionKeyName;
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
/// <summary>
/// Use sql connection string by user define.
/// </summary>
public SqlDatabaseManager(string SqlConnectionKeyName, string SqlConnectionString)
{
sqlConnectionKeyName = SqlConnectionKeyName;
sqlConnectionString = SqlConnectionString;
sqlConnection = new SqlConnection(sqlConnectionString);
}
#endregion
#region ========== Property ==========
/// <summary>
/// Gets or sets Sql connection key name from web.config.
/// </summary>
public virtual string ConnectionKeyName
{
get { return sqlConnectionKeyName; }
set
{
sqlConnectionKeyName = value;
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
}
/// <summary>
/// Gets or sets Sql connection.
/// </summary>
public virtual string ConnectionString
{
get { return sqlConnectionString; }
set
{
sqlConnectionString = value;
sqlConnection = new SqlConnection(sqlConnectionString);
}
}
/// <summary>
/// Gets or sets Sql command.
/// </summary>
public virtual string CommandString
{
get { return sqlCommandString; }
set
{
sqlCommandString = ConvertDateCommand(value);
sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
commandMessage = "You must execute command.";
commandSuccess = false;
rowsAffected = 0;
if (transaction)
sqlCommand.Transaction = sqlTransaction;
}
}
/// <summary>
/// Check for Sql command.
/// </summary>
public virtual bool IsSuccess
{
get { return commandSuccess; }
}
/// <summary>
/// Gets message from Sql command.
/// </summary>
public virtual string Message
{
get { return commandMessage; }
}
/// <summary>
/// Gets Number of rows affected.
/// </summary>
public virtual int RowsAffected
{
get { return rowsAffected; }
}
#endregion
#region ========== Method ==========
/// <summary>
/// Add the parameter value to the sql command.
/// </summary>
/// <param name="ParameterName">The name of Parameter.</param>
/// <param name="ParameterValue">The value to be added.</param>
public virtual void AddParameter(string ParameterName, object ParameterValue)
{
sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
}
/// <summary>
/// Start Sql Transaction.
/// </summary>
public virtual void TransactionStart()
{
transaction = true;
errorCommand = new List<string>();
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);
}
/// <summary>
/// Execute Sql Transaction.
/// </summary>
/// <returns>Result of transaction.</returns>
public virtual bool ExecuteTransaction()
{
transaction = false;
if (errorCommand.Count == 0)
{
sqlTransaction.Commit();
commandMessage = "All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>";
commandSuccess = true;
}
else
{
sqlTransaction.Rollback();
string ErrorText = "Some command has error. <font color=\"red\">Transaction RollBack.</font><br />Error in: <br />";
foreach (string aErrorSqlCommand in errorCommand)
{
ErrorText += aErrorSqlCommand + "<br />";
}
commandMessage = ErrorText;
commandSuccess = false;
}
errorCommand.Clear();
if (sqlConnection.State == ConnectionState.Open)
sqlConnection.Close();
sqlTransaction.Dispose();
sqlCommand.Dispose();
sqlConnection.Dispose();
return commandSuccess;
}
/// <summary>
/// Execute Query Sql command.
/// </summary>
/// <returns>Query data in DataTable.</returns>
public virtual DataTable ExecuteQuery()
{
DataTable dataTable = new DataTable();
try
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
if (!transaction)
{
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
}
rowsAffected = dataTable.Rows.Count;
return dataTable;
}
/// <summary>
/// Execute Scalar Sql command.
/// </summary>
/// <returns>Object of value.</returns>
public virtual object ExecuteScalar()
{
object Result = 0;
try
{
if (transaction)
{
Result = sqlCommand.ExecuteScalar();
}
else
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
Result = sqlCommand.ExecuteScalar();
sqlConnection.Close();
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
AddErrorCommand(sqlCommandString, ex.Message);
}
return Result;
}
/// <summary>
/// Execute Non Query Sql command.
/// </summary>
/// <returns>Result of execute command.</returns>
public virtual bool ExecuteNonQuery()
{
rowsAffected = 0;
try
{
if (transaction)
{
rowsAffected = sqlCommand.ExecuteNonQuery();
}
else
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
rowsAffected = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
AddErrorCommand(sqlCommandString, ex.Message);
}
return commandSuccess;
}
/// <summary>
/// Build error message.
/// </summary>
/// <param name="Message">Message string.</param>
/// <returns>Error message string.</returns>
public virtual string ErrorMessage(string MessageString)
{
return "<font color=\"red\">Command error.</font> " + MessageString;
}
/// <summary>
/// Add error sql command to string collections.
/// </summary>
/// <param name="commandString">The sql command.</param>
/// <param name="errorMessage">The error message.</param>
private void AddErrorCommand(string commandString, string errorMessage)
{
errorCommand.Add(commandString + " <font color=\"red\">[Error message: " + errorMessage + "]</font>");
}
/// <summary>
/// Convert native command to sql command.
/// </summary>
/// <param name="commandString">The native sql command.</param>
/// <returns>The standard sql command.</returns>
private string ConvertDateCommand(string commandString)
{
string SmallDateTimePattern = "[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
Regex SmallDateTimeRgx = new Regex(SmallDateTimePattern);
foreach (Match SmallDateTimeMatchCase in SmallDateTimeRgx.Matches(commandString))
{
string MatchCasePattern = "^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]";
Regex MatchCaseRgx = new Regex(MatchCasePattern);
Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
string TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(SmallDateTime, ").Replace(")", ", 103)"));
}
string DateTimePattern = "[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
Regex DateTimeRgx = new Regex(DateTimePattern);
foreach (Match DateTimeMatchCase in DateTimeRgx.Matches(commandString))
{
string MatchCasePattern = "^[dD][aA][tT][eE][tT][iI][mM][eE]";
Regex MatchCaseRgx = new Regex(MatchCasePattern);
Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
string TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(DateTime, ").Replace(")", ", 103)"));
}
return commandString;
}
#endregion
}
#endregion
#region ========== Class SqlVarBinary ==========
/// <summary>
/// Summary description for BinaryData
/// </summary>
public class SqlVarBinary
{
public SqlVarBinary()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Convert to byte[].
/// </summary>
public static byte[] Convert(Stream BinaryStream, int StreamLength)
{
BinaryReader BinaryRead = new BinaryReader(BinaryStream);
byte[] binaryData = BinaryRead.ReadBytes(StreamLength);
return binaryData;
}
}
#endregion
#region ========== Class SqlDateTime ==========
/// <summary>
/// Summary description for SqlDateTime
/// </summary>
public class SqlDateTime
{
//ควรกำหนด culture ใน web.config เป็น th
//
//ตัวอย่างใน web.config
//<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>
public SqlDateTime()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Convert to DataTime DataType with d/M/yyyy format.
/// </summary>
public static DateTime Convert(string DateString)
{
return DateTime.ParseExact(DateString, "d/M/yyyy", CultureInfo.InvariantCulture);
}
/// <summary>
/// Convert to DataTime DataType with user define format.
/// </summary>
public static DateTime Convert(string DateString, string DateFormat)
{
return DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
}
}
#endregion
|
|
|
|
|
Date :
2010-03-26 17:28:23 |
By :
tungman |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
เบื่อแกล้งเด็กแระ เอาโค้ดไปแล้วกัน
TestGridView.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 TestGridView : System.Web.UI.Page
{
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDatabaseManager Sql1 = new SqlDatabaseManager();
Sql1.CommandString = "Select * From [Global_UserClass]";
DataTable1 = Sql1.ExecuteQuery();
DataTable2 = DataTable1.Clone();
ViewState["DataTable1"] = DataTable1;
ViewState["DataTable2"] = DataTable2;
}
else
{
DataTable1 = (DataTable)ViewState["DataTable1"];
DataTable2 = (DataTable)ViewState["DataTable2"];
}
TemplateField TemplateField1 = new TemplateField();
TemplateField1.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "CheckBox");
GridView1.Columns.Add(TemplateField1);
GridView1.DataKeyNames = new String[] { "ClassID" };
GridView1.DataSource = DataTable1;
GridView1.DataBind();
CheckBox CheckBox2 = new CheckBox();
CheckBox2.ID = "CheckBox2";
TemplateField TemplateField2 = new TemplateField();
TemplateField2.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "CheckBox");
GridView2.Columns.Add(TemplateField2);
GridView2.DataKeyNames = new String[] { "ClassID" };
GridView2.DataSource = DataTable2;
GridView2.DataBind();
Button1.Click += new EventHandler(Button1_Click);
Button2.Click += new EventHandler(Button2_Click);
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DataTable1.Rows.Count > 0)
{
foreach (GridViewRow gridviewRow in GridView1.Rows)
{
CheckBox CheckBox1 = (CheckBox)gridviewRow.Cells[0].Controls[0];
if (CheckBox1.Checked == true)
{
DataTable2.ImportRow(DataTable1.Rows[gridviewRow.RowIndex]);
DataTable1.Rows[gridviewRow.RowIndex].Delete();
}
}
DataTable1.AcceptChanges();
GridView1.DataSource = DataTable1;
GridView1.DataBind();
GridView2.DataSource = DataTable2;
GridView2.DataBind();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (DataTable2.Rows.Count > 0)
{
foreach (GridViewRow gridviewRow in GridView2.Rows)
{
CheckBox CheckBox2 = (CheckBox)gridviewRow.Cells[0].Controls[0];
if (CheckBox2.Checked == true)
{
DataTable1.ImportRow(DataTable2.Rows[gridviewRow.RowIndex]);
DataTable2.Rows[gridviewRow.RowIndex].Delete();
}
}
DataTable2.AcceptChanges();
GridView1.DataSource = DataTable1;
GridView1.DataBind();
GridView2.DataSource = DataTable2;
GridView2.DataBind();
}
}
}
// Here is the code for building the template field
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
public GridViewTemplate(DataControlRowType type, string colname)
{
templateType = type;
columnName = colname;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
CheckBox checkAll = new CheckBox();
//checkAll.Attributes.Add("onclick", "javascript:checkAll(this.form);");
container.Controls.Add(checkAll);
break;
case DataControlRowType.DataRow:
CheckBox cb = new CheckBox();
cb.Text = "";
//cb.Attributes.Add("onclick", "javascript:colorRow(this);");
container.Controls.Add(cb);
break;
default:
break;
}
}
}
|
|
|
|
|
Date :
2010-03-26 18:15:57 |
By :
tungman |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 03
|