PDA

View Full Version : آپدیت داده درون دیتا گرید



faramarz_s
چهارشنبه 02 مهر 1382, 09:00 صبح
برای نمایش داده های قابل آپدیت درون خود دیتا گرید مایکروسافت مثال زیر را پیشنهاد داده:

<script runat="server">
SqlConnection myConnection;

protected void Page_Load(Object Src, EventArgs E)
{
// Create a connection to the "pubs" SQL database located on the
// local computer.
myConnection = new SqlConnection ("server=localhost;" +
"database=pubs;Trusted_Connection=Yes");
// Determine whether the page is a postback. If it is not a
// postback, call BindGrid.
if (!IsPostBack) BindGrid();
}
// Create an index to the DataGrid row that is clicked and
// call BindGrid.
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}

// Cancel resets the index to the row's previous settings.
public void MyDataGrid_Cancel(Object sender,
DataGridCommandEventArgs E)
{
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
// When the Update link is clicked, build a SQL UPDATE command,
// connect to the database, update the row's information in the
// database, and rebind the DataGrid to show the updated information.
public void MyDataGrid_Update(Object sender,
DataGridCommandEventArgs E)
{
String updateCmd = "UPDATE Authors SET au_id = @Id," +
" au_lname = @LName, au_fname = @FName, phone = @Phone," +
" address = @Address, city = @City, state = @State," +
" zip = @Zip, contract = @Contract WHERE au_id = @Id;";
SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);
myCommand.Parameters.Add(new SqlParameter("@Id",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@LName",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@FName",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@Phone",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@Address",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@City",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@State",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@Zip",
SqlDbType.VarChar));
myCommand.Parameters.Add(new SqlParameter("@Contract",
SqlDbType.VarChar));
// Initialize the SqlCommand "@Id" parameter to the ID of the
// row that must be clicked.
myCommand.Parameters["@Id"].Value =
MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
// Create an array of column names.
String[] cols = {"@Id","@LName","@FName","@Phone",
"@Address", "@City","@State","@Zip","@Contract"};
// Iterate through the columns, checking for empty values.
// Skip the first, second, and last columns. If an empty value
// is found, display an error message box. Also initialize the
// SqlCommand parameter values.
int numCols = E.Item.Cells.Count;
for (int i=2; i<numCols-1; i++)
{
String colvalue = ((TextBox)E.Item.Cells[i].Controls[0]).Text;
if (i<6 && colvalue == "")
{
Message.InnerHtml = "ERROR: Null values not allowed for" +
" Author ID, Name or Phone";
Message.Style["color"] = "red";
return;
}
myCommand.Parameters[cols[i-1]].Value = colvalue;
}
// Append the last field, converting true/false values to 0/1.
if (String.Compare(((TextBox)E.Item.Cells
[numCols-1].Controls[0]).Text, "true", true)==0)
myCommand.Parameters["@Contract"].Value = "1";
else
myCommand.Parameters["@Contract"].Value = "0";
// Connect to the database and update the information.
myCommand.Connection.Open();
// Test whether the data was updated and display the
//appropriate message to the user.
try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>Record Updated.</b><br>";
MyDataGrid.EditItemIndex = -1;
}
catch (SqlException e)
{
if (e.Number == 2627)
Message.InnerHtml = "ERROR: A record already exists" +
" with the same primary key";
else
Message.InnerHtml = "ERROR: Could not update record," +
" please ensure the fields are correctly filled out";
Message.Style["color"] = "red";
}
// Close the connection.
myCommand.Connection.Close();
// Show the updated information.
BindGrid();
}

// The BindGrid procedure connects to the database and implements
// a SQL SELECT query to get all data in the "Authors" table.
public void BindGrid()
{
SqlConnection myConnection = new SqlConnection(
"server=localhost;database=pubs;Trusted_Connection= Yes");
SqlDataAdapter myCommand = new SqlDataAdapter(
"SELECT * FROM authors", myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
MyDataGrid.DataSource=ds;
MyDataGrid.DataBind();
}

نکته ای که هست عدم نمایش دیتا گرید بدون هیچ پیغام خطا!
کجای کار ایراد دارد؟ :?:

Vahid_Nasiri
چهارشنبه 02 مهر 1382, 11:23 صبح
کانکشن استرینگ


("server=localhost;" +
"database=pubs;Trusted_Connection=Yes"

باید مطابق تنظیمات SQL-Server شما تنظیم شود. یوزر آی دی و پسورد می خواهد و سپس تراستد باید حذف شود.

SoheilKH
چهارشنبه 02 مهر 1382, 11:46 صبح
فرامرز آگه میشه آدرس مثال رو بنویس

faramarz_s
چهارشنبه 02 مهر 1382, 16:31 عصر
در MSDNکلمه sqlException را جستجو کرده آنگاه در قسمت زیرش بخش Update a Database را
انتخاب کنید.
سهیل آقا!

ParWin
یک شنبه 06 مهر 1382, 11:53 صبح
بسم الله النور
سلام منم دقیقا" همین مشکلو دارم اگه فهمیدید چرا فیلدای DataGrid رو به TextBox تبدیل نمی کنه خدا خیرتون بده به منم بگید. منتظرم
پی پلاس پلاس مستاصل!

SoheilKH
یک شنبه 06 مهر 1382, 12:09 عصر
اقا فرامرز
نمی دونم چرا شما می ری راه دور!! :cry:
مگه مثالهای Quick Start خوب توضیح نداده.
به نظر من این آدرس خوب توضیح داده:
http://localhost/quickstart/aspplus/samples/webforms/data/VB/datagrid6.aspx

faramarz_s
دوشنبه 07 مهر 1382, 10:55 صبح
ممکنه متن برنامه را یا بنوسید یا اتچ کنید چون من سمپلها را نمی توانم نصب کنم. :wink:

SoheilKH
یک شنبه 27 مهر 1382, 03:47 صبح
با سلام
آقا خیلی معضرت این قدر دیر جواب سئوال شما را می دم نمی دونم الان بدرد می خوره یا نه اما....

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="Acme" %>

<html>

<script language="VB" runat="server">

Dim MyConnection As SqlConnection

Sub Page_Load(Sender As Object, E As EventArgs)

MyConnection = New _
SqlConnection("server=(local)\NetSDK;database=pubs;Integrated Security=SSPI")

If Not (IsPostBack)
BindGrid()
End If
End Sub

Sub MyDataGrid_Edit(Sender As Object, E As DataGridCommandEventArgs)

MyDataGrid.EditItemIndex = CInt(E.Item.ItemIndex)
BindGrid()
End Sub

Sub MyDataGrid_Cancel(Sender As Object, E As DataGridCommandEventArgs)

MyDataGrid.EditItemIndex = -1
BindGrid()
End Sub

Sub MyDataGrid_Update(Sender As Object, E As DataGridCommandEventArgs)

Dim DS As DataSet
Dim MyCommand As SqlCommand

Dim UpdateCmd As String = "UPDATE Authors SET au_id = @Id, au_lname = @LName, " & _
"au_fname = @FName, phone = @Phone, address = @Address, city = @City, " & _
"state = @State, zip = @Zip, contract = @Contract where au_id = @Id"

MyCommand = New SqlCommand(UpdateCmd, MyConnection)

MyCommand.Parameters.Add(New SqlParameter("@Id", SqlDbType.NVarChar, 11))
MyCommand.Parameters.Add(New SqlParameter("@LName", SqlDbType.NVarChar, 40))
MyCommand.Parameters.Add(New SqlParameter("@FName", SqlDbType.NVarChar, 20))
MyCommand.Parameters.Add(New SqlParameter("@Phone", SqlDbType.NChar, 12))
MyCommand.Parameters.Add(New SqlParameter("@Address", SqlDbType.NVarChar, 40))
MyCommand.Parameters.Add(New SqlParameter("@City", SqlDbType.NVarChar, 20))
MyCommand.Parameters.Add(New SqlParameter("@State", SqlDbType.NChar, 2))
MyCommand.Parameters.Add(New SqlParameter("@Zip", SqlDbType.NChar, 5))
MyCommand.Parameters.Add(New SqlParameter("@Contract", SqlDbType.NVarChar,1))

MyCommand.Parameters("@Id").Value = MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))

Dim Cols As String() = {"@Id","@LName","@FName","@Phone","@Address", _
"@City","@State","@Zip","@Contract"}

Dim NumCols As Integer = E.Item.Cells.Count
Message.InnerHtml = ""

Dim I As Integer
For I=2 To NumCols-2 'skip first, second and last column

Dim CurrentTextBox As System.Web.UI.WebControls.TextBox
CurrentTextBox = E.Item.Cells(I).Controls(0)
Dim ColValue As String = CurrentTextBox.Text


' check for invalid values
Select Case Cols(i-1)
Case "@LName"
If Not InputValidator.IsValidAnsiName(colvalue)
Message.InnerHtml &= "ERROR: Last Name - " & InputValidator.AnsiNameErrorString & "<br>"
End If
Case "@FName"
If Not InputValidator.IsValidAnsiName(colvalue)
Message.InnerHtml &= "ERROR: First Name - " & InputValidator.AnsiNameErrorString & "<br>"
End If
Case "@Phone"
If Not InputValidator.IsValidAnsiPhoneNumber(colvalue)
Message.InnerHtml &= "ERROR: Phone - " & InputValidator.AnsiPhoneErrorString & "<br>"
End If
Case "@Address"
If Not InputValidator.IsValidAnsiAddress(colvalue)
Message.InnerHtml &= "ERROR: Address - " & InputValidator.AnsiAddressErrorString & "<br>"
End If
Case "@City"
If Not InputValidator.IsValidAnsiCityOrState(colvalue)
Message.InnerHtml &= "ERROR: City - " & InputValidator.AnsiCityStateErrorString & "<br>"
End If
Case "@State"
If Not InputValidator.IsValidAnsiTwoCharacterState(colval ue)
Message.InnerHtml &= "ERROR: State - " & InputValidator.AnsiTwoCharacterStateErrorString & "<br>"
End If
Case "@Zip"
If Not InputValidator.IsValidFiveDigitZipCode(colvalue)
Message.InnerHtml &= "ERROR: Zip Code - " & InputValidator.AnsiBasicZipCodeErrorString & "<br>"
End If
End Select

' Check for null values in required fields
If I<6 And ColValue = ""
Message.InnerHtml &= "ERROR: Null values not allowed for " & Cols(i-1) & "<br>"
End If

MyCommand.Parameters(Cols(I-1)).Value = ColValue
Next

If Message.InnerHtml <> ""
Message.Style("color") = "red"
Return
End If

' Append last row, converting true/false values to 0/1
Dim ContractTextBox As System.Web.UI.WebControls.TextBox
ContractTextBox = E.Item.Cells(NumCols-1).Controls(0)
If ContractTextBox.Text.ToLower(CultureInfo.Invariant Culture) = "true"
MyCommand.Parameters("@Contract").Value = "1"
Else
MyCommand.Parameters("@Contract").Value = "0"
End If

MyCommand.Connection.Open()

Try
MyCommand.ExecuteNonQuery()
Message.InnerHtml = "<b>Record Updated</b><br>" & UpdateCmd.ToString()
MyDataGrid.EditItemIndex = -1
Catch Exp As SQLException
If Exp.Number = 2627
Message.InnerHtml = "ERROR: A record already exists with the same " & _
"primary key"
Else
Message.InnerHtml = "ERROR: Could not update record, please " & _
"ensure the fields are correctly filled out"
End If
Message.Style("color") = "red"
End Try

MyCommand.Connection.Close()

BindGrid()
End Sub

Sub BindGrid()

Dim DS As DataSet
Dim MyCommand As SqlDataAdapter
MyCommand = new SqlDataAdapter("select * from Authors", MyConnection)

DS = new DataSet()
MyCommand.Fill(DS, "Authors")

MyDataGrid.DataSource=DS.Tables("Authors").DefaultView
MyDataGrid.DataBind()
End Sub

</script>

<body style="font: 10pt verdana">

<form runat="server">

<h3><font face="Verdana">Updating a Row of Data</font></h3>

<span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/><p>

<ASP:DataGrid id="MyDataGrid" runat="server"
Width="800"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
DataKeyField="au_id"
>

<Columns>
<asp:EditCommandColumn EditText="Edit" CancelText="Cancel"
UpdateText="Update" ItemStyle-Wrap="false"/>
</Columns>

</ASP:DataGrid>

</form>

</body>
</html>


راستی چرا نمی تونی سمپل quickstart را نصب کنی

tazekar
یک شنبه 27 مهر 1382, 10:26 صبح
آقا سهیل دیر و زود رو وللش
بابا فارسی رو پاس بدار
معضرت چیه ؟
درستش معزرته داداش :evil:

SoheilKH
دوشنبه 28 مهر 1382, 04:12 صبح
:D :D :D کیبوردم خراب بود :oops:
بعد حدود 20 روز تازه تونستم به اینترنت وصل بشم دیگه اینقدر خوشحال بودم که ...
اما خان داداش این دفعه رو زیر سیبیلی رد کن .دیگه تکرار نمی شه :wink:

tazekar
دوشنبه 28 مهر 1382, 16:40 عصر
این دفه رو باشه :twisted:
ولی تکرار نشه ها :mrgreen: