我需要使用rowcommand删除编辑更新3tier架构中的gridview [英] I need delete edit update the gridview in 3tier architecture using rowcommand

查看:48
本文介绍了我需要使用rowcommand删除编辑更新3tier架构中的gridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用层:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using ENT;
using BAL;

//pls give me server side code for me to make rowcommand event run
namespace myTeststudent3tier
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        int Flag = 0;
        private int flag;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                LoadGrid();
            }
        }
        private void LoadGrid()
        {
            

                TBAL BL = new TBAL();
                DataTable DT = new DataTable();
                DT = BL.Select();
                GridView1.DataSource = DT;//when i ru with this code i got error says Both DataSource and DataSourceID are defined on 'GridView1'.  Remove one definition.
               
                GridView1.DataBind();
            }
    }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditRow")//this code got from surfing the net
            {
                int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
                GridView1.EditIndex = rowindex;
                LoadGrid();
            }
            else if (e.CommandName == "CancelUpdate")//this code got from surfing the net
            {
                GridView1.EditIndex = -1;

                LoadGrid();

            }
            else if (e.CommandName == "UpdateRow")
            {
                //here ihave to write a code for updaterow in template but i dontknow how to do but this is the code u used but this one will not implement nothing on templatefield
                int val = Convert.ToInt16(Session["PKId"]);
                testENT EN = new testENT()
                {
                    StrName = txtName.Text,
                    IntGender = Convert.ToInt16(DropDownList1.SelectedValue.ToString()),
                    IntId = val

                };
                TBAL objBAL = new TBAL();

                Flag = objBAL.Update(EN);
            }



            else if (e.CommandName == "DeleteRow")
            {
                int val = Convert.ToInt16(e.CommandArgument.ToString());
                Session["PKId"] = val.ToString();


                testENT obj = new testENT()
                   {
                       IntId = val



                   };
                Flag = new TBAL().Delete(obj);
                LoadGrid();
                if (Flag > 0)
                {

                    LoadGrid();

                    lblDisplay.Text = "Record deleted Successfully ";
                }
                else
                {
                    lblDisplay.Text = "try Again";
                }
            }
        }

        protected void btn1_Click(object sender, EventArgs e)//this piece of code is k here is used to insert then ican use separate button to make update delete but i wanna need to do it in rowcommand//pls help
        {
            testENT ENT = new testENT()
            {
                StrName = txtName.Text,
                IntGender = Convert.ToInt16(DropDownList1.SelectedValue.ToString())
            };


            TBAL objBal = new TBAL();
            Flag = objBal.Insert(ENT);

            if (Page.IsValid)
            {



                txtName.Text = "";
                DropDownList1.SelectedIndex = -1;

                lblDisplay.Text = "Record Inserted Successfully ";
                LoadGrid();
            }
            else
            {
                lblDisplay.Text = "pls try again ";
            }
        }
    }


}



ENT:




ENT:

public class testENT
    {
        public int IntId { get; set; }
        public string StrName { get; set; }
        public int IntGender { get; set; }
    }
}



DAL:


DAL:

 public class DBconnection
    {
        public String ConnString = ConfigurationManager.ConnectionStrings["SQLconnection"].ConnectionString;
        public SqlConnection sql;
        public void DBCon()
        {

            sql = new SqlConnection(ConnString);
        }

        public void Connect()
        {
            if (sql.State == ConnectionState.Closed)
                sql.Open();
        }

        public void DisConnect()
        {
            if (sql.State == ConnectionState.Open)
                sql.Close();
        }
    }
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENT;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
   public class testDAL:DBconnection
    {
       testENT ENTObj = new testENT();
        int Flag = 0;
        public int Insert(testENT ENTObj)
        {
            DBCon();
            Connect();
            SqlCommand cmd = new SqlCommand("tblStudentInsert", sql);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", ENTObj.StrName);
            cmd.Parameters.AddWithValue("@Gender", ENTObj.IntGender);
            Flag = cmd.ExecuteNonQuery();
            DisConnect();
            return Flag;
        }
        public int Delete(testENT ENTObj)
        {
            DBCon();
            Connect();
            SqlCommand cmd = new SqlCommand("tblStudentDelete", sql);
           cmd.Parameters.AddWithValue("@Id", ENTObj.IntId);
            cmd.CommandType = CommandType.StoredProcedure;
            Flag = cmd.ExecuteNonQuery();
            DisConnect();
            return Flag;
        }
        public int Update(testENT ENTObj)
        {
            DBCon();
            Connect();

            SqlCommand cmd = new SqlCommand("tblStudentUpdate", sql);
            cmd.Parameters.AddWithValue("@Name", ENTObj.StrName);
            cmd.Parameters.AddWithValue("@Gender", ENTObj.IntGender);
            cmd.Parameters.AddWithValue("@Id", ENTObj.IntId);
            cmd.CommandType = CommandType.StoredProcedure;
            Flag = cmd.ExecuteNonQuery();
            DisConnect();
            return Flag;
        }
        public DataTable Select()
        {
            DBCon();
            Connect();
            DataTable dt1 = new DataTable();



            SqlCommand cmd = new SqlCommand("tblStudentSelect", sql);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adt = new SqlDataAdapter(cmd);
            adt.Fill(dt1);
            DisConnect();
            return dt1;
        }


        public DataTable Edit(testENT obj)
        {
            DBCon();
            Connect();
            DataTable dt1 = new DataTable();



            SqlCommand cmd = new SqlCommand("tblStudentEdit", sql);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Id", obj.IntId);
            SqlDataAdapter adt = new SqlDataAdapter(cmd);
            adt.Fill(dt1);
            
            DisConnect();
            return dt1;
        }
    }

}



BAL:


BAL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENT;
using DAL;
using System.Data; 

namespace BAL
{
    public class TBAL
    {
         public int Insert(testENT ENobj)
        {
            return new testDAL().Insert(ENobj);
        }
        public int Delete(testENT ENobj)
        {
            return new testDAL().Delete(ENobj);
        }
        public DataTable Select()
        {
            return new testDAL().Select();
        }
        public DataTable Edit(testENT ENobj)
        {
            return new testDAL().Edit(ENobj);
        }
        public int Update(testENT ENobj)
        {
            return new testDAL().Update(ENobj);
        }
    }

    }



Designfilrcodexhtml


Designfilrcodexhtml

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="myTeststudent3tier.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>
 
    <div>
    
        Name:<asp:TextBox ID="txtName" runat="server">
        <asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ErrorMessage="Name is Required" ControlToValidate="txtName">
        <asp:DropDownList ID="DropDownList1"  runat="server">
        
        <asp:ListItem Text="selectGender" Value="-1"> 
         
            <asp:ListItem Value="1" Text="Male">
            <asp:ListItem Value="2" Text="Female">
            
        
        <asp:RequiredFieldValidator ID="RequiredFieldValidatorGender" runat="server" ErrorMessage="Gender is Required" InitialValue="-1" ControlToValidate="DropDownList1">
    
        <asp:Button ID="btn1" runat="server" Text="Submit" onclick="btn1_Click" />
    
        <br>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 

        CellPadding="4" DataKeyNames="Id" DataSourceID="SqlDataSource1" 

        ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
        <asp:templatefield>
        <itemtemplate>
            <asp:LinkButton ID="lnkEdit" CommandArgument='<%# Eval("Id") %>' CommandName ="EditRow"  Forecolor="#8c4510" runat="server">Edit
            <asp:LinkButton ID="lnkDelete" CommandArgument='<%# Eval("Id") %>' CommandName ="DeleteRow"  runat="server">Delete
            
            <edititemtemplate>
            <asp:LinkButton ID="lnkUpdate" CommandArgument='<%# Eval("Id") %>' CommandName ="UpdateRow"  runat="server">Update
            <asp:LinkButton ID="lnkCancel" CommandArgument='<%# Eval("Id") %>' CommandName ="CancelUpdate"  runat="server">Cancel
            
        
        
            
            <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                <itemtemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'>
                
                <edititemtemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'>
                
            
            <asp:TemplateField HeaderText="Name" SortExpression="Name">
                <itemtemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'>
                
                <edititemtemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'>
                
            
            <asp:TemplateField HeaderText="Gender" SortExpression="Gender">
                <itemtemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Gender") %>'>
                
                <edititemtemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Gender") %>'>
                
            
                 <asp:templatefield>
                <itemtemplate>
    
            <asp:templatefield>
                <itemtemplate>

        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 

        ConnectionString="<%$ ConnectionStrings:SQLconnection %>" 

        DeleteCommand="DELETE FROM [tblStudent] WHERE [Id] = @Id" 

        InsertCommand="INSERT INTO [tblStudent] ([Name], [Gender]) VALUES (@Name, @Gender)" 

        SelectCommand="SELECT * FROM [tblStudent]" 

        UpdateCommand="UPDATE [tblStudent] SET [Name] = @Name, [Gender] = @Gender WHERE [Id] = @Id">
        <deleteparameters>
            <asp:Parameter Name="Id" Type="Int32" />
        
        <insertparameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Gender" Type="String" />
        
        <updateparameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Gender" Type="String" />
            <asp:Parameter Name="Id" Type="Int32" />
        
    
    <asp:Label ID="lblDisplay" runat="server" Text="Label">





What I have tried:



I tried it insert button works but rowcommand event doesnt works and bindgrid sometimes appears both datasoure and datasourceid are in same gridview1



What I have tried:

I tried it insert button works but rowcommand event doesnt works and bindgrid sometimes appears both datasoure and datasourceid are in same gridview1

推荐答案

ConnectionStrings:SQLconnection %>\"

DeleteCommand=\"DELETE FROM [tblStudent] WHERE [Id] = @Id\"

InsertCommand=\"INSERT INTO [tblStudent] ([Name], [Gender]) VALUES (@Name, @Gender)\"

SelectCommand=\"SELECT * FROM [tblStudent]\"

UpdateCommand=\"UPDATE [tblStudent] SET [Name] = @Name, [Gender] = @Gender WHERE [Id] = @Id\">
<deleteparameters>
<asp:Parameter Name=\"Id\" Type=\"Int32\" />

<insertparameters>
<asp:Parameter Name=\"Name\" Type=\"String\" />
<asp:Parameter Name=\"Gender\" Type=\"String\" />

<updateparameters>
<asp:Parameter Name=\"Name\" Type=\"String\" />
<asp:Parameter Name=\"Gender\" Type=\"String\" />
<asp:Parameter Name=\"Id\" Type=\"Int32\" />


<asp:Label ID=\"
lblDisplay\" runat=\"server\" Text=\"Label\">
ConnectionStrings:SQLconnection %>" DeleteCommand="DELETE FROM [tblStudent] WHERE [Id] = @Id" InsertCommand="INSERT INTO [tblStudent] ([Name], [Gender]) VALUES (@Name, @Gender)" SelectCommand="SELECT * FROM [tblStudent]" UpdateCommand="UPDATE [tblStudent] SET [Name] = @Name, [Gender] = @Gender WHERE [Id] = @Id"> <deleteparameters> <asp:Parameter Name="Id" Type="Int32" /> <insertparameters> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="Gender" Type="String" /> <updateparameters> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="Gender" Type="String" /> <asp:Parameter Name="Id" Type="Int32" /> <asp:Label ID="lblDisplay" runat="server" Text="Label">





What I have tried:



I tried it insert button works but rowcommand event doesnt works and bindgrid sometimes appears both datasoure and datasourceid are in same gridview1



What I have tried:

I tried it insert button works but rowcommand event doesnt works and bindgrid sometimes appears both datasoure and datasourceid are in same gridview1


Quote:

i need to bind and give me solution for rowcommand edit,delete,update

i need to bind and give me solution for rowcommand edit,delete,update





We do not do your homework: it is set for a reason.它就是为了让你思考你被告知的事情,并试着理解它。 It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.



Try it yourself, you may find it is not as difficult as you think!

You have insert working, so it should be simple for you to add the rest, if you think about it.



If you meet a specific problem, then please ask about that and we will do our best to help.但我们不打算为你做这一切!



We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!
You have insert working, so it should be simple for you to add the rest, if you think about it.

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren't going to do it all for you!


这篇关于我需要使用rowcommand删除编辑更新3tier架构中的gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆