如何使用C#在gridview中编辑,删除,更新,取消 [英] how to edit ,delete,update,cancel in a gridview using C#
本文介绍了如何使用C#在gridview中编辑,删除,更新,取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一张桌子
T1
-------------------------- ------------------------
I create a table
T1
--------------------------------------------------
SlNo int Unchecked
WebsiteName varchar(100) Unchecked
PortId varchar(100) Unchecked
Createdate date Unchecked
那么我设计一个网格视图并从数据库中获取价值
THEN I DESIGN A GRID VIEW AND GET THE VALUE FROM DB LIKE THIS
<asp:GridView ID="gvDetails" DataKeyNames="SlNo,Websitename" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<columns><asp:TemplateField><edititemtemplate>
<asp:Button ID="BtnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="20px" Width="20px" Text="update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel" ToolTip="Cancel" Height="20px" Width="20px" Text="Cancel"/>
</edititemtemplate><itemtemplate>
<asp:Button ID="BtnUpdate" CommandName="Update" runat="server" ToolTip="Update" Height="20px" Width="20px" Text="update" />
<asp:Button ID="BtnCancel" runat="server" CommandName="Cancel" ToolTip="Cancel" Height="20px" Width="20px" Text="Cancel"/>
</itemtemplate><footertemplate>
<asp:Button ID="btnAdd" runat="server" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</footertemplate><asp:TemplateField HeaderText="SlNo"><edititemtemplate>
<asp:Label ID="lbleditusr" runat="server" Text=' <%#Container.DataItemIndex+1%> '/>
</edititemtemplate><asp:TemplateField HeaderText="SiteName"><edititemtemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="redirect" Text='<%# DataBinder.Eval(Container.DataItem, "WebsiteName")%>' ToolTip="redirect"></edititemtemplate><itemtemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="redirect" Text='<%# DataBinder.Eval(Container.DataItem, "WebsiteName")%>' ToolTip="redirect"></itemtemplate><footertemplate>
<asp:TextBox ID="txtsitename" runat="server"/>
<asp:RequiredFieldValidator ID="rfvsitename" runat="server" ControlToValidate="txtsitename" Text="*" ValidationGroup="validaiton"/>
</footertemplate></columns>
代码背后(.CS文件)
CODE BEHIND(.CS FILE)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
public partial class gridview_testing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
SqlConnection con = new SqlConnection(sqlCon);
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
SqlConnection con = new SqlConnection(sqlCon);
con.Open();
SqlCommand cmd = new SqlCommand("select WebsiteName from Websitedtls", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
SqlConnection con = new SqlConnection(sqlCon);
int SlNo = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string sitename = gvDetails.DataKeys[e.RowIndex].Values["SiteName"].ToString();
TextBox txtsitename = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtsitename");
con.Open();
SqlCommand cmd = new SqlCommand("update Websitedtls set WebsiteName='" + txtsitename + "' where SlNo=" + SlNo, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = sitename + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
SqlConnection con = new SqlConnection(sqlCon);
int SlNo = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["SlNo"].ToString());
string sitename = gvDetails.DataKeys[e.RowIndex].Values["sitename"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Websitedtls where SlNo=" + SlNo, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = sitename + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
string sqlCon = ConfigurationManager.ConnectionStrings["cnstr"].ToString();
SqlConnection con = new SqlConnection(sqlCon);
if (e.CommandName.Equals("AddNew"))
{
TextBox txtsitename = (TextBox)gvDetails.FooterRow.FindControl("txtsitename");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Websitedtls(WebsiteName) values( '" +txtsitename.Text + "' )", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtsitename.Text + " Details inserted successfully";
}
else {
lblresult.ForeColor = Color.Red;
lblresult.Text = txtsitename.Text + " Details not inserted";
}}}}
但它显示错误,就像这样
DataBinding:''系统。 Data.DataRowView''不包含名为''SlNo''的属性。
PLS帮助我解决这个问题
BUT IT SHOWS ERROR, LIKE THIS
DataBinding: ''System.Data.DataRowView'' does not contain a property with the name ''SlNo''.
PLS HELP ME TO SOLVE THIS
推荐答案
当您设置GridView的''DataKeyNames =UserId,UserName''时,您的源数据集必须包含UserId和UserName列,错误是因为你没有从数据库中检索UserId和UserName并尝试将其作为DataKey绑定到GridView。
As you have set ''DataKeyNames="UserId,UserName"'' of your GridView then your source dataset must have the column ''UserId'' and ''UserName'', The error is becouse you are not retriving UserId, and UserName from database and trying to bind it as the DataKey to the GridView.
这篇关于如何使用C#在gridview中编辑,删除,更新,取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文