当编辑操作同时发生时,在 ASP.NET 中的 GridView 控件中执行删除操作

发布于 2024-11-15 23:22:14 字数 1930 浏览 4 评论 0原文

目前我正在使用这是在 GridView 控件中执行编辑的标准方法。但这允许我一次只能执行一项操作。在我的应用程序中,当一个字段的一个值发生更改时,当用户单击“更新”时。应更新行,并且还应触发一个删除查询。

我尝试使用手动编辑

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
               AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
               DataSourceID="sdsample1" Visible="False" OnRowEditing="GridView1_OnRowEditing" OnRowUpdated="GridView1_OnRowUpdated">

- 想要获取后端当前编辑行的 CheckboxField 值及其 gridview 中的第 8 列

<asp:CheckBoxField   DataField="Goal_Type" HeaderText="Goal_Type" 
                       SortExpression="Goal_Type" />


protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
{

((CheckBox)GridView1.Rows[GridView1.SelectedIndex].FindControl("Goal_Type"));
CheckBox chk2 = ((CheckBox)GridView1.Rows[GridView1.EditIndex].Cells[7].Controls[0]);
goal_type =Convert.ToString(chk2.Checked);
if(goal_type.Equals("False"))
Goal_flag.Value ="0";
else
Goal_flag.Value = "1";
}

然后一旦我获取复选框字段的值设置一些标志变量,我就在中执行删除操作下面的函数

protected void GridView1_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
{

CheckBox chk2 = ((CheckBox)GridView1.Rows[e.AffectedRows].Cells[7].Controls[0]);
Boolean goal_type = chk2.Checked;
if (goal_type == true && Goal_flag.Value.Equals("0"))
{

string connectionString =
WebConfigurationManager.ConnectionStrings["DataCollectionConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd;
int ID = Convert.ToInt32(((TextBox)GridView1.Rows[e.AffectedRows].FindControl("ID")).Text);
 

cmd =new SqlCommand("Delete from XXX WHERE (ID = " + ID + ") ", con);
 

cmd.CommandType =

CommandType.Text;
con.Open();

 

cmd.ExecuteNonQuery();

con.Close();

}

我在“GridView1_OnRowEditing”函数本身收到此错误 指数超出范围。必须为非负数且小于集合的大小。 参数名称:index

请让我知道我在 GridView 中执行同时操作的方法是否正确。

Currently I am using the which is the standard way to perform Editing in a GridView control. But this allows me to perform only one operation at a time.In my application when one value of one field changes , when user clicks on "Update". Rows should be updated and also one delete query should be fired.

I tried using the manually editing

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
               AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
               DataSourceID="sdsample1" Visible="False" OnRowEditing="GridView1_OnRowEditing" OnRowUpdated="GridView1_OnRowUpdated">

-- Want to get the CheckboxField value of the current edit row in the backnd and its the 8 column in the gridview

<asp:CheckBoxField   DataField="Goal_Type" HeaderText="Goal_Type" 
                       SortExpression="Goal_Type" />


protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
{

((CheckBox)GridView1.Rows[GridView1.SelectedIndex].FindControl("Goal_Type"));
CheckBox chk2 = ((CheckBox)GridView1.Rows[GridView1.EditIndex].Cells[7].Controls[0]);
goal_type =Convert.ToString(chk2.Checked);
if(goal_type.Equals("False"))
Goal_flag.Value ="0";
else
Goal_flag.Value = "1";
}

Then once I get the value of checkbox field set some flag variable , I perform a delete operation in the below function

protected void GridView1_OnRowUpdated(object sender, GridViewUpdatedEventArgs e)
{

CheckBox chk2 = ((CheckBox)GridView1.Rows[e.AffectedRows].Cells[7].Controls[0]);
Boolean goal_type = chk2.Checked;
if (goal_type == true && Goal_flag.Value.Equals("0"))
{

string connectionString =
WebConfigurationManager.ConnectionStrings["DataCollectionConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd;
int ID = Convert.ToInt32(((TextBox)GridView1.Rows[e.AffectedRows].FindControl("ID")).Text);
 

cmd =new SqlCommand("Delete from XXX WHERE (ID = " + ID + ") ", con);
 

cmd.CommandType =

CommandType.Text;
con.Open();

 

cmd.ExecuteNonQuery();

con.Close();

}

I am getting this error at the "GridView1_OnRowEditing" function itself
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Please let me know if my approach is correct in doing the simultaneous operation in GridView.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情泪▽动烟 2024-11-22 23:22:14

使用 RowEditing 事件进行多次更新。正如此 问题 中提到的:

protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    e.Cancel = true;
    ASPxGridView1.CancelEdit();
}

为了查找控件,我建议采用以下方法:本期提到:
http://www.devexpress.com/Support/Center/p/Q91970.aspx

protected void grd_ReportChartSeries_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
    ASPxGridView gridView = sender as ASPxGridView;
    ASPxComboBox combo = gridView.FindEditRowCellTemplateControl(gridView.Columns["Data2"] as GridViewDataColumn, "comboData2") as ASPxComboBox;
    object data2 = combo.Value;

    combo = gridView.FindEditRowCellTemplateControl(gridView.Columns["ID"] as GridViewDataColumn, "comboID") as ASPxComboBox;
    object ID = combo.Value;

    ASPxTextBox textBox = gridView.FindEditRowCellTemplateControl(gridView.Columns["Data1"] as GridViewDataColumn, "txtData1") as ASPxTextBox;
    object data1 = textBox.Value;

    ds = Session["DataSet"] as DataSet;
    DataTable dataTable = ds.Tables[0];
    DataRow row = dataTable.Rows.Find(e.Keys[0]);
    row["ID"] = ID;
    row["Data1"] = data1;
    row["Data2"] = data2;
    gridView.CancelEdit();
    e.Cancel = true;

}

或者您可以通过一个存储过程调用来进行更新和删除。

Use the RowEditing event for the multiple updates. As mentioned in this issue:

protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    datasource.UpdateCommand = "UPDATE .....";
    datasource.Update(...);

    e.Cancel = true;
    ASPxGridView1.CancelEdit();
}

For finding the control I recommend the approach that is mentioned in this issue:
http://www.devexpress.com/Support/Center/p/Q91970.aspx

protected void grd_ReportChartSeries_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
    ASPxGridView gridView = sender as ASPxGridView;
    ASPxComboBox combo = gridView.FindEditRowCellTemplateControl(gridView.Columns["Data2"] as GridViewDataColumn, "comboData2") as ASPxComboBox;
    object data2 = combo.Value;

    combo = gridView.FindEditRowCellTemplateControl(gridView.Columns["ID"] as GridViewDataColumn, "comboID") as ASPxComboBox;
    object ID = combo.Value;

    ASPxTextBox textBox = gridView.FindEditRowCellTemplateControl(gridView.Columns["Data1"] as GridViewDataColumn, "txtData1") as ASPxTextBox;
    object data1 = textBox.Value;

    ds = Session["DataSet"] as DataSet;
    DataTable dataTable = ds.Tables[0];
    DataRow row = dataTable.Rows.Find(e.Keys[0]);
    row["ID"] = ID;
    row["Data1"] = data1;
    row["Data2"] = data2;
    gridView.CancelEdit();
    e.Cancel = true;

}

Or you could do the update and delete through one stored procedure call.

人心善变 2024-11-22 23:22:14
  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="Class3417.Employee" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
                <tr>
                    <td>Name :</td>
                    <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
                </tr>

                 <tr>
                    <td>Gender :</td>
                    <td><asp:RadioButtonList ID="rblgender" runat="server" RepeatColumns="3">
                        </asp:RadioButtonList></td>
                </tr>

                 <tr>
                    <td>Country :</td>
                    <td><asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList></td>
                </tr>

                 <tr>
                    <td>Hobbies :</td>
                    <td><asp:CheckBoxList ID="cblhobbies" runat="server" RepeatColumns="4">
                        </asp:CheckBoxList></td>
                </tr>

                 <tr>
                    <td>Files :</td>
                    <td><asp:FileUpload ID="fufiles" runat="server"></asp:FileUpload></td>
                </tr>

                 <tr>
                    <td></td>
                    <td><asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" /></td>
                </tr>

                 <tr>
                    <td></td>
                    <td><asp:GridView ID="grd" runat="server" DataKeyNames="empid" AutoGenerateColumns="false" OnRowDataBound="grd_RowDataBound" OnRowEditing="grd_RowEditing"  OnRowDeleting="grd_RowDeleting" OnRowCancelingEdit="grd_RowCancelingEdit" OnRowUpdating="grd_RowUpdating" >
                        <Columns>
                            <asp:TemplateField HeaderText="Name">
                                <ItemTemplate>
                                    <%#Eval("name") %>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtnameedit" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Gender">
                                <ItemTemplate>
                                    <%#Eval("gname") %>
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:RadioButtonList ID="rblgenderedit" runat="server" RepeatColumns="3">

                                    </asp:RadioButtonList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Country">
                                <ItemTemplate>
                                    <%#Eval("cname") %>
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:DropDownList ID="ddlcountryedit" runat="server" ></asp:DropDownList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Hobbies">
                                <ItemTemplate>
                                    <%#Eval("Hobbies") %>
                                </ItemTemplate>
                                 <EditItemTemplate>
                                    <asp:CheckBoxList ID="cblhobbiesedit" runat="server" RepeatColumns="4"></asp:CheckBoxList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Files">
                                <ItemTemplate>
                                    <asp:Image ID="img" runat="server" ImageUrl='<%#Eval("files","~/uploads/{0}") %>' Width="80px" Height="60px" /> 
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:FileUpload ID="fufileedit" runat="server" ></asp:FileUpload>
                                </EditItemTemplate>
                            </asp:TemplateField>

                            <asp:CommandField ShowEditButton="true" />
                            <asp:CommandField ShowDeleteButton="true" />                            
                        </Columns>
                        </asp:GridView></td>
                </tr>
            </table>
    </div>
    </form>
</body>
</html>






  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 System.IO;

    namespace Class3417
    {
        public partial class Employee : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Fill_Country(ddlcountry);
                    Fill_Gender(rblgender);
                    Fill_Hobbies(cblhobbies);
                    Fill_Grid();
                }
            }
            public void Fill_Grid()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_country_gender_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grd.DataSource = ds;
                    grd.DataBind();
                }
                con.Close();
            }
            public void Fill_Country(DropDownList ddl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_country_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddl.DataValueField = "cid";
                    ddl.DataTextField = "cname";
                    ddl.DataSource = ds;
                    ddl.DataBind();
                    ddl.Items.Insert(0, new ListItem("--Select Country--", "0"));
                }
                con.Close();
            }

            public void Fill_Gender(RadioButtonList rbl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();`
                SqlCommand cmd = new SqlCommand("usp_gender_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    rbl.DataValueField = "gid";
                    rbl.DataTextField = "gname";
                    rbl.DataSource = ds;
                    rbl.DataBind();
                }
                con.Close();
            }

            public void Fill_Hobbies(CheckBoxList cbl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_hobbies_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    cbl.DataValueField = "hid";
                    cbl.DataTextField = "hname";
                    cbl.DataSource = ds;
                    cbl.DataBind();
                }
                con.Close();
            }

            protected void btnsave_Click(object sender, EventArgs e)
            {
                string HOB = "";
                for (int i = 0; i < cblhobbies.Items.Count; i++)
                {
                    if (cblhobbies.Items[i].Selected == true)
                    {
                        HOB += cblhobbies.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fufiles.PostedFile.FileName);
                fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid", 0);
                cmd.Parameters.AddWithValue("name", txtname.Text);
                cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                cmd.Parameters.AddWithValue("hobbies", HOB);
                cmd.Parameters.AddWithValue("files",  FN);
                cmd.ExecuteNonQuery();
                con.Close();
                Fill_Grid();
            }

            protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
            {
                grd.EditIndex = e.NewEditIndex;
                Fill_Grid();
            }

            protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                    {
                        DropDownList DDLC = (DropDownList)e.Row.FindControl("ddlcountryedit");
                        Fill_Country(DDLC);


                        RadioButtonList RBLG = (RadioButtonList)e.Row.FindControl("rblgenderedit");
                        Fill_Gender(RBLG);

                        CheckBoxList CBLH = (CheckBoxList)e.Row.FindControl("cblhobbiesedit");
                        Fill_Hobbies(CBLH);

                        DataRowView drv = (DataRowView)e.Row.DataItem;
                        DDLC.SelectedValue = drv["country"].ToString();
                        RBLG.SelectedValue = drv["gender"].ToString();
                        ViewState["FL"] = drv["files"].ToString();

                        string[] arr = drv["hobbies"].ToString().Split(',');
                        CBLH.ClearSelection();
                        for (int i = 0; i < CBLH.Items.Count; i++)
                        {
                            for (int j = 0; j < arr.Length; j++)
                            {
                                if (CBLH.Items[i].Text == arr[j])
                                {
                                    CBLH.Items[i].Selected = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            protected void grd_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                grd.EditIndex = -1;
                Fill_Grid();
            }

            protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                TextBox TBN = (TextBox)grd.Rows[e.RowIndex].FindControl("txtnameedit");
                RadioButtonList RBLGG = (RadioButtonList)grd.Rows[e.RowIndex].FindControl("rblgenderedit");
                DropDownList DDLCC = (DropDownList)grd.Rows[e.RowIndex].FindControl("ddlcountryedit");
                CheckBoxList CBLHH = (CheckBoxList)grd.Rows[e.RowIndex].FindControl("cblhobbiesedit");
                FileUpload FUFF = (FileUpload)grd.Rows[e.RowIndex].FindControl("fufileedit");
                string IDD = grd.DataKeys[e.RowIndex].Value.ToString();



                string HOB = "";
                for (int i = 0; i < CBLHH.Items.Count; i++)
                {
                    if (CBLHH.Items[i].Selected == true)
                    {
                        HOB += CBLHH.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = Path.GetFileName(FUFF.PostedFile.FileName);

                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid", IDD);
                cmd.Parameters.AddWithValue("name", TBN.Text);
                cmd.Parameters.AddWithValue("gender", RBLGG.SelectedValue);
                cmd.Parameters.AddWithValue("country", DDLCC.SelectedValue);
                cmd.Parameters.AddWithValue("hobbies", HOB);
                if (FN != "")
                {
                    FN = DateTime.Now.Ticks.ToString() + FN;
                    cmd.Parameters.AddWithValue("files", FN);
                    File.Delete(Server.MapPath("uploads" + "\\" + ViewState["FL"]));
                    FUFF.SaveAs(Server.MapPath("uploads" + "\\" + FN));
                }
                else
                {
                    cmd.Parameters.AddWithValue("files", ViewState["FL"]);
                }
                cmd.ExecuteNonQuery();
                con.Close();
                grd.EditIndex = -1;
                Fill_Grid();
            }

            protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid",int.Parse(grd.DataKeys[e.RowIndex].Value.ToString()));
                cmd.ExecuteNonQuery();
                con.Close();
                Fill_Grid();
            }
        }
    }
  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="Class3417.Employee" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
                <tr>
                    <td>Name :</td>
                    <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
                </tr>

                 <tr>
                    <td>Gender :</td>
                    <td><asp:RadioButtonList ID="rblgender" runat="server" RepeatColumns="3">
                        </asp:RadioButtonList></td>
                </tr>

                 <tr>
                    <td>Country :</td>
                    <td><asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList></td>
                </tr>

                 <tr>
                    <td>Hobbies :</td>
                    <td><asp:CheckBoxList ID="cblhobbies" runat="server" RepeatColumns="4">
                        </asp:CheckBoxList></td>
                </tr>

                 <tr>
                    <td>Files :</td>
                    <td><asp:FileUpload ID="fufiles" runat="server"></asp:FileUpload></td>
                </tr>

                 <tr>
                    <td></td>
                    <td><asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" /></td>
                </tr>

                 <tr>
                    <td></td>
                    <td><asp:GridView ID="grd" runat="server" DataKeyNames="empid" AutoGenerateColumns="false" OnRowDataBound="grd_RowDataBound" OnRowEditing="grd_RowEditing"  OnRowDeleting="grd_RowDeleting" OnRowCancelingEdit="grd_RowCancelingEdit" OnRowUpdating="grd_RowUpdating" >
                        <Columns>
                            <asp:TemplateField HeaderText="Name">
                                <ItemTemplate>
                                    <%#Eval("name") %>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtnameedit" runat="server" Text='<%#Eval("name") %>'></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Gender">
                                <ItemTemplate>
                                    <%#Eval("gname") %>
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:RadioButtonList ID="rblgenderedit" runat="server" RepeatColumns="3">

                                    </asp:RadioButtonList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Country">
                                <ItemTemplate>
                                    <%#Eval("cname") %>
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:DropDownList ID="ddlcountryedit" runat="server" ></asp:DropDownList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                            <asp:TemplateField HeaderText="Hobbies">
                                <ItemTemplate>
                                    <%#Eval("Hobbies") %>
                                </ItemTemplate>
                                 <EditItemTemplate>
                                    <asp:CheckBoxList ID="cblhobbiesedit" runat="server" RepeatColumns="4"></asp:CheckBoxList>
                                </EditItemTemplate>
                            </asp:TemplateField>

                             <asp:TemplateField HeaderText="Files">
                                <ItemTemplate>
                                    <asp:Image ID="img" runat="server" ImageUrl='<%#Eval("files","~/uploads/{0}") %>' Width="80px" Height="60px" /> 
                                </ItemTemplate>
                                  <EditItemTemplate>
                                    <asp:FileUpload ID="fufileedit" runat="server" ></asp:FileUpload>
                                </EditItemTemplate>
                            </asp:TemplateField>

                            <asp:CommandField ShowEditButton="true" />
                            <asp:CommandField ShowDeleteButton="true" />                            
                        </Columns>
                        </asp:GridView></td>
                </tr>
            </table>
    </div>
    </form>
</body>
</html>






  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 System.IO;

    namespace Class3417
    {
        public partial class Employee : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Fill_Country(ddlcountry);
                    Fill_Gender(rblgender);
                    Fill_Hobbies(cblhobbies);
                    Fill_Grid();
                }
            }
            public void Fill_Grid()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_country_gender_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grd.DataSource = ds;
                    grd.DataBind();
                }
                con.Close();
            }
            public void Fill_Country(DropDownList ddl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_country_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddl.DataValueField = "cid";
                    ddl.DataTextField = "cname";
                    ddl.DataSource = ds;
                    ddl.DataBind();
                    ddl.Items.Insert(0, new ListItem("--Select Country--", "0"));
                }
                con.Close();
            }

            public void Fill_Gender(RadioButtonList rbl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();`
                SqlCommand cmd = new SqlCommand("usp_gender_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    rbl.DataValueField = "gid";
                    rbl.DataTextField = "gname";
                    rbl.DataSource = ds;
                    rbl.DataBind();
                }
                con.Close();
            }

            public void Fill_Hobbies(CheckBoxList cbl)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_hobbies_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    cbl.DataValueField = "hid";
                    cbl.DataTextField = "hname";
                    cbl.DataSource = ds;
                    cbl.DataBind();
                }
                con.Close();
            }

            protected void btnsave_Click(object sender, EventArgs e)
            {
                string HOB = "";
                for (int i = 0; i < cblhobbies.Items.Count; i++)
                {
                    if (cblhobbies.Items[i].Selected == true)
                    {
                        HOB += cblhobbies.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fufiles.PostedFile.FileName);
                fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid", 0);
                cmd.Parameters.AddWithValue("name", txtname.Text);
                cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                cmd.Parameters.AddWithValue("hobbies", HOB);
                cmd.Parameters.AddWithValue("files",  FN);
                cmd.ExecuteNonQuery();
                con.Close();
                Fill_Grid();
            }

            protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
            {
                grd.EditIndex = e.NewEditIndex;
                Fill_Grid();
            }

            protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                    {
                        DropDownList DDLC = (DropDownList)e.Row.FindControl("ddlcountryedit");
                        Fill_Country(DDLC);


                        RadioButtonList RBLG = (RadioButtonList)e.Row.FindControl("rblgenderedit");
                        Fill_Gender(RBLG);

                        CheckBoxList CBLH = (CheckBoxList)e.Row.FindControl("cblhobbiesedit");
                        Fill_Hobbies(CBLH);

                        DataRowView drv = (DataRowView)e.Row.DataItem;
                        DDLC.SelectedValue = drv["country"].ToString();
                        RBLG.SelectedValue = drv["gender"].ToString();
                        ViewState["FL"] = drv["files"].ToString();

                        string[] arr = drv["hobbies"].ToString().Split(',');
                        CBLH.ClearSelection();
                        for (int i = 0; i < CBLH.Items.Count; i++)
                        {
                            for (int j = 0; j < arr.Length; j++)
                            {
                                if (CBLH.Items[i].Text == arr[j])
                                {
                                    CBLH.Items[i].Selected = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            protected void grd_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                grd.EditIndex = -1;
                Fill_Grid();
            }

            protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                TextBox TBN = (TextBox)grd.Rows[e.RowIndex].FindControl("txtnameedit");
                RadioButtonList RBLGG = (RadioButtonList)grd.Rows[e.RowIndex].FindControl("rblgenderedit");
                DropDownList DDLCC = (DropDownList)grd.Rows[e.RowIndex].FindControl("ddlcountryedit");
                CheckBoxList CBLHH = (CheckBoxList)grd.Rows[e.RowIndex].FindControl("cblhobbiesedit");
                FileUpload FUFF = (FileUpload)grd.Rows[e.RowIndex].FindControl("fufileedit");
                string IDD = grd.DataKeys[e.RowIndex].Value.ToString();



                string HOB = "";
                for (int i = 0; i < CBLHH.Items.Count; i++)
                {
                    if (CBLHH.Items[i].Selected == true)
                    {
                        HOB += CBLHH.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = Path.GetFileName(FUFF.PostedFile.FileName);

                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid", IDD);
                cmd.Parameters.AddWithValue("name", TBN.Text);
                cmd.Parameters.AddWithValue("gender", RBLGG.SelectedValue);
                cmd.Parameters.AddWithValue("country", DDLCC.SelectedValue);
                cmd.Parameters.AddWithValue("hobbies", HOB);
                if (FN != "")
                {
                    FN = DateTime.Now.Ticks.ToString() + FN;
                    cmd.Parameters.AddWithValue("files", FN);
                    File.Delete(Server.MapPath("uploads" + "\\" + ViewState["FL"]));
                    FUFF.SaveAs(Server.MapPath("uploads" + "\\" + FN));
                }
                else
                {
                    cmd.Parameters.AddWithValue("files", ViewState["FL"]);
                }
                cmd.ExecuteNonQuery();
                con.Close();
                grd.EditIndex = -1;
                Fill_Grid();
            }

            protected void grd_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("empid",int.Parse(grd.DataKeys[e.RowIndex].Value.ToString()));
                cmd.ExecuteNonQuery();
                con.Close();
                Fill_Grid();
            }
        }
    }
極樂鬼 2024-11-22 23:22:14
how to insert ,update,delete and show data in gridview  


  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="Test29317.Employee" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <ajax:ToolkitScriptManager ID="kk" runat="server"></ajax:ToolkitScriptManager>
            <div>
                <table>
                    <tr>
                        <td>Name :</td>
                        <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
                    </tr>

                     <tr>
                        <td>Gender :</td>
                        <td><asp:RadioButtonList ID="rblgender" runat="server" RepeatColumns="3">
                            <asp:ListItem Text="male" Value="1" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="female" Value="2"></asp:ListItem>
                            <asp:ListItem Text="others" Value="3"></asp:ListItem>
                            </asp:RadioButtonList></td>
                    </tr>

                     <tr>
                        <td>Country :</td>
                        <td><asp:DropDownList ID="ddlcountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlcountry_SelectedIndexChanged"></asp:DropDownList></td>
                    </tr>

                     <tr>
                        <td>State :</td>
                        <td><asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList></td>
                    </tr>

                     <tr>
                        <td>Hobbies :</td>
                        <td><asp:CheckBoxList ID="cblhobbies" runat="server" RepeatColumns="4">
                             <asp:ListItem Text="cricket" Value="1"></asp:ListItem>
                            <asp:ListItem Text="football" Value="2"></asp:ListItem>
                            <asp:ListItem Text="music" Value="3"></asp:ListItem>
                            <asp:ListItem Text="movies" Value="4"></asp:ListItem>
                            <asp:ListItem Text="badminton" Value="5"></asp:ListItem>
                            <asp:ListItem Text="chess" Value="6"></asp:ListItem>
                            <asp:ListItem Text="dancing" Value="7"></asp:ListItem>
                            <asp:ListItem Text="dangal" Value="8"></asp:ListItem>
                            </asp:CheckBoxList></td>
                    </tr>

                     <tr>
                        <td>Files :</td>
                        <td><asp:FileUpload ID="fufiles" runat="server"></asp:FileUpload></td>
                    </tr>

                     <tr>
                        <td>Date of Birth :</td>
                        <td><asp:TextBox ID="txtdob" runat="server"></asp:TextBox>
                            <ajax:CalendarExtender ID="call" runat="server" PopupButtonID="txtdob" PopupPosition="BottomRight" TargetControlID="txtdob"></ajax:CalendarExtender>
                        </td>
                    </tr>

                     <tr>
                        <td>IsActive :</td>
                        <td><asp:CheckBox ID="chkisactive" runat="server"></asp:CheckBox></td>
                    </tr>

                     <tr>
                        <td></td>
                        <td><asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" /></td>
                    </tr>

                     <tr>
                        <td></td>
                        <td><asp:GridView ID="grd" runat="server" AutoGenerateColumns="false" OnRowCommand="grd_RowCommand">
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <%#Eval("name") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Gender">
                                    <ItemTemplate>
                                        <%#Eval("gender").ToString()=="1"?"male":Eval("gender").ToString()=="2"?"female":"others" %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Country">
                                    <ItemTemplate>
                                        <%#Eval("cname") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="State">
                                    <ItemTemplate>
                                        <%#Eval("sname") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Hobbies">
                                    <ItemTemplate>
                                        <%#Eval("Hobbies") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="date of birth">
                                    <ItemTemplate>
                                        <%#Convert.ToDateTime(Eval("dob").ToString()).ToShortDateString() %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Files">
                                    <ItemTemplate>
                                        <asp:Image ID="img" runat="server" ImageUrl='<%#Eval("files","~/uploads/{0}") %>' Width="80px" Height="60px" /> 
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Is Active">
                                    <ItemTemplate>
                                        <%#Eval("isactive").ToString()=="1"?"yes":"no" %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                  <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtnedit" runat="server" Text="Edit" CommandArgument='<%#Eval("empid") %>' CommandName="EDT"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtndelet" runat="server" Text="Delete" CommandArgument='<%#Eval("empid") %>' CommandName="Del"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            </asp:GridView></td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
    </html>






    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 System.IO;

    namespace Test29317
    {
        public partial class Employee : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Fill_Country();
                    ddlstate.Items.Insert(0, new ListItem("--Select State--", "0"));
                    Fill_Grid();
                }
            }
            public void Fill_Grid()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_country_state_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grd.DataSource = ds;
                    grd.DataBind();
                }
                con.Close();
            }

            public void Fill_Country()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_country_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddlcountry.DataValueField = "cid";
                    ddlcountry.DataTextField = "cname";
                    ddlcountry.DataSource = ds;
                    ddlcountry.DataBind();
                    ddlcountry.Items.Insert(0, new ListItem("--Select Country--", "0"));
                }
                con.Close();
            }

            protected void btnsave_Click(object sender, EventArgs e)
            {
                string HOB = "";
                for (int i = 0; i < cblhobbies.Items.Count; i++)
                {
                    if (cblhobbies.Items[i].Selected == true)
                    {
                        HOB += cblhobbies.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = Path.GetFileName(fufiles.PostedFile.FileName);
                if (btnsave.Text == "Save")
                {

                    fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));

                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("empid", 0);
                    cmd.Parameters.AddWithValue("name", txtname.Text);
                    cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                    cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                    cmd.Parameters.AddWithValue("state", ddlstate.SelectedValue);
                    cmd.Parameters.AddWithValue("hobbies", HOB);
                    cmd.Parameters.AddWithValue("dob", txtdob.Text);
                    cmd.Parameters.AddWithValue("files", DateTime.Now.Ticks.ToString() + FN);
                    cmd.Parameters.AddWithValue("isactive", chkisactive.Checked == true ? 1 : 0);
                    cmd.ExecuteNonQuery();
                    con.Close();

                }
                else
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("empid", ViewState["ID"]);
                    cmd.Parameters.AddWithValue("name", txtname.Text);
                    cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                    cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                    cmd.Parameters.AddWithValue("state", ddlstate.SelectedValue);
                    cmd.Parameters.AddWithValue("hobbies", HOB);
                    cmd.Parameters.AddWithValue("dob", txtdob.Text);
                    if (FN != "")
                    {
                        FN = DateTime.Now.Ticks.ToString() + FN;
                        cmd.Parameters.AddWithValue("files", FN);
                        File.Delete(Server.MapPath("uploads" + "\\" + ViewState["FL"]));
                        fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));

                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("files", ViewState["FL"]);
                    }
                    cmd.Parameters.AddWithValue("isactive", chkisactive.Checked == true ? 1 : 0);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                Fill_Grid();
            }
            public void Fill_State_by_country(int CIDD)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_state_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataView dv = new DataView(ds.Tables[0]);
                    dv.RowFilter = "cid=" + CIDD;
                    ddlstate.DataValueField = "sid";
                    ddlstate.DataTextField = "sname";
                    ddlstate.DataSource = dv;
                    ddlstate.DataBind();
                    ddlstate.Items.Insert(0, new ListItem("--Select State--", "0"));
                }
                con.Close();
            }
            protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
            {
                Fill_State_by_country(int.Parse(ddlcountry.SelectedValue));
            }

            protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "EDT")
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_edit", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@eid", e.CommandArgument);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        txtname.Text = ds.Tables[0].Rows[0]["name"].ToString();
                        rblgender.SelectedValue = ds.Tables[0].Rows[0]["gender"].ToString();
                        txtdob.Text = ds.Tables[0].Rows[0]["dob"].ToString();
                        ddlcountry.SelectedValue = ds.Tables[0].Rows[0]["country"].ToString();
                        Fill_State_by_country(int.Parse(ds.Tables[0].Rows[0]["country"].ToString()));
                        ddlstate.SelectedValue = ds.Tables[0].Rows[0]["state"].ToString();
                        if (ds.Tables[0].Rows[0]["isactive"].ToString() == "1")
                        {
                            chkisactive.Checked = true;
                        }
                        else
                        {
                            chkisactive.Checked = false;
                        }
                        string[] arr = ds.Tables[0].Rows[0]["hobbies"].ToString().Split(',');
                        cblhobbies.ClearSelection();
                        for (int i = 0; i < cblhobbies.Items.Count; i++)
                        {
                            for (int j = 0; j < arr.Length; j++)
                            {
                                if (cblhobbies.Items[i].Text == arr[j])
                                {
                                    cblhobbies.Items[i].Selected = true;
                                    break;
                                }
                            }
                        }




                        ViewState["FL"] = ds.Tables[0].Rows[0]["files"].ToString();
                        btnsave.Text = "Update";
                        ViewState["ID"] = e.CommandArgument;
                        con.Close();

                    }
                }

                else if (e.CommandName == "Del")
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@empid", e.CommandArgument);
                    cmd.ExecuteNonQuery();
                    con.Close();
                    Fill_Grid();

                    }
                }
            }
        }
how to insert ,update,delete and show data in gridview  


  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee.aspx.cs" Inherits="Test29317.Employee" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <ajax:ToolkitScriptManager ID="kk" runat="server"></ajax:ToolkitScriptManager>
            <div>
                <table>
                    <tr>
                        <td>Name :</td>
                        <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
                    </tr>

                     <tr>
                        <td>Gender :</td>
                        <td><asp:RadioButtonList ID="rblgender" runat="server" RepeatColumns="3">
                            <asp:ListItem Text="male" Value="1" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="female" Value="2"></asp:ListItem>
                            <asp:ListItem Text="others" Value="3"></asp:ListItem>
                            </asp:RadioButtonList></td>
                    </tr>

                     <tr>
                        <td>Country :</td>
                        <td><asp:DropDownList ID="ddlcountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlcountry_SelectedIndexChanged"></asp:DropDownList></td>
                    </tr>

                     <tr>
                        <td>State :</td>
                        <td><asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList></td>
                    </tr>

                     <tr>
                        <td>Hobbies :</td>
                        <td><asp:CheckBoxList ID="cblhobbies" runat="server" RepeatColumns="4">
                             <asp:ListItem Text="cricket" Value="1"></asp:ListItem>
                            <asp:ListItem Text="football" Value="2"></asp:ListItem>
                            <asp:ListItem Text="music" Value="3"></asp:ListItem>
                            <asp:ListItem Text="movies" Value="4"></asp:ListItem>
                            <asp:ListItem Text="badminton" Value="5"></asp:ListItem>
                            <asp:ListItem Text="chess" Value="6"></asp:ListItem>
                            <asp:ListItem Text="dancing" Value="7"></asp:ListItem>
                            <asp:ListItem Text="dangal" Value="8"></asp:ListItem>
                            </asp:CheckBoxList></td>
                    </tr>

                     <tr>
                        <td>Files :</td>
                        <td><asp:FileUpload ID="fufiles" runat="server"></asp:FileUpload></td>
                    </tr>

                     <tr>
                        <td>Date of Birth :</td>
                        <td><asp:TextBox ID="txtdob" runat="server"></asp:TextBox>
                            <ajax:CalendarExtender ID="call" runat="server" PopupButtonID="txtdob" PopupPosition="BottomRight" TargetControlID="txtdob"></ajax:CalendarExtender>
                        </td>
                    </tr>

                     <tr>
                        <td>IsActive :</td>
                        <td><asp:CheckBox ID="chkisactive" runat="server"></asp:CheckBox></td>
                    </tr>

                     <tr>
                        <td></td>
                        <td><asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" /></td>
                    </tr>

                     <tr>
                        <td></td>
                        <td><asp:GridView ID="grd" runat="server" AutoGenerateColumns="false" OnRowCommand="grd_RowCommand">
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <%#Eval("name") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Gender">
                                    <ItemTemplate>
                                        <%#Eval("gender").ToString()=="1"?"male":Eval("gender").ToString()=="2"?"female":"others" %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Country">
                                    <ItemTemplate>
                                        <%#Eval("cname") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="State">
                                    <ItemTemplate>
                                        <%#Eval("sname") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Hobbies">
                                    <ItemTemplate>
                                        <%#Eval("Hobbies") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="date of birth">
                                    <ItemTemplate>
                                        <%#Convert.ToDateTime(Eval("dob").ToString()).ToShortDateString() %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Files">
                                    <ItemTemplate>
                                        <asp:Image ID="img" runat="server" ImageUrl='<%#Eval("files","~/uploads/{0}") %>' Width="80px" Height="60px" /> 
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField HeaderText="Is Active">
                                    <ItemTemplate>
                                        <%#Eval("isactive").ToString()=="1"?"yes":"no" %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                  <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtnedit" runat="server" Text="Edit" CommandArgument='<%#Eval("empid") %>' CommandName="EDT"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lnkbtndelet" runat="server" Text="Delete" CommandArgument='<%#Eval("empid") %>' CommandName="Del"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            </asp:GridView></td>
                    </tr>
                </table>
            </div>
        </form>
    </body>
    </html>






    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 System.IO;

    namespace Test29317
    {
        public partial class Employee : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    Fill_Country();
                    ddlstate.Items.Insert(0, new ListItem("--Select State--", "0"));
                    Fill_Grid();
                }
            }
            public void Fill_Grid()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_emp_country_state_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grd.DataSource = ds;
                    grd.DataBind();
                }
                con.Close();
            }

            public void Fill_Country()
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_country_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddlcountry.DataValueField = "cid";
                    ddlcountry.DataTextField = "cname";
                    ddlcountry.DataSource = ds;
                    ddlcountry.DataBind();
                    ddlcountry.Items.Insert(0, new ListItem("--Select Country--", "0"));
                }
                con.Close();
            }

            protected void btnsave_Click(object sender, EventArgs e)
            {
                string HOB = "";
                for (int i = 0; i < cblhobbies.Items.Count; i++)
                {
                    if (cblhobbies.Items[i].Selected == true)
                    {
                        HOB += cblhobbies.Items[i].Text + ",";
                    }
                }
                HOB = HOB.TrimEnd(',');
                string FN = "";
                FN = Path.GetFileName(fufiles.PostedFile.FileName);
                if (btnsave.Text == "Save")
                {

                    fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));

                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("empid", 0);
                    cmd.Parameters.AddWithValue("name", txtname.Text);
                    cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                    cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                    cmd.Parameters.AddWithValue("state", ddlstate.SelectedValue);
                    cmd.Parameters.AddWithValue("hobbies", HOB);
                    cmd.Parameters.AddWithValue("dob", txtdob.Text);
                    cmd.Parameters.AddWithValue("files", DateTime.Now.Ticks.ToString() + FN);
                    cmd.Parameters.AddWithValue("isactive", chkisactive.Checked == true ? 1 : 0);
                    cmd.ExecuteNonQuery();
                    con.Close();

                }
                else
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_insert_update", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("empid", ViewState["ID"]);
                    cmd.Parameters.AddWithValue("name", txtname.Text);
                    cmd.Parameters.AddWithValue("gender", rblgender.SelectedValue);
                    cmd.Parameters.AddWithValue("country", ddlcountry.SelectedValue);
                    cmd.Parameters.AddWithValue("state", ddlstate.SelectedValue);
                    cmd.Parameters.AddWithValue("hobbies", HOB);
                    cmd.Parameters.AddWithValue("dob", txtdob.Text);
                    if (FN != "")
                    {
                        FN = DateTime.Now.Ticks.ToString() + FN;
                        cmd.Parameters.AddWithValue("files", FN);
                        File.Delete(Server.MapPath("uploads" + "\\" + ViewState["FL"]));
                        fufiles.SaveAs(Server.MapPath("uploads" + "\\" + FN));

                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("files", ViewState["FL"]);
                    }
                    cmd.Parameters.AddWithValue("isactive", chkisactive.Checked == true ? 1 : 0);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
                Fill_Grid();
            }
            public void Fill_State_by_country(int CIDD)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                SqlCommand cmd = new SqlCommand("usp_state_select", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataView dv = new DataView(ds.Tables[0]);
                    dv.RowFilter = "cid=" + CIDD;
                    ddlstate.DataValueField = "sid";
                    ddlstate.DataTextField = "sname";
                    ddlstate.DataSource = dv;
                    ddlstate.DataBind();
                    ddlstate.Items.Insert(0, new ListItem("--Select State--", "0"));
                }
                con.Close();
            }
            protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
            {
                Fill_State_by_country(int.Parse(ddlcountry.SelectedValue));
            }

            protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "EDT")
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_edit", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@eid", e.CommandArgument);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        txtname.Text = ds.Tables[0].Rows[0]["name"].ToString();
                        rblgender.SelectedValue = ds.Tables[0].Rows[0]["gender"].ToString();
                        txtdob.Text = ds.Tables[0].Rows[0]["dob"].ToString();
                        ddlcountry.SelectedValue = ds.Tables[0].Rows[0]["country"].ToString();
                        Fill_State_by_country(int.Parse(ds.Tables[0].Rows[0]["country"].ToString()));
                        ddlstate.SelectedValue = ds.Tables[0].Rows[0]["state"].ToString();
                        if (ds.Tables[0].Rows[0]["isactive"].ToString() == "1")
                        {
                            chkisactive.Checked = true;
                        }
                        else
                        {
                            chkisactive.Checked = false;
                        }
                        string[] arr = ds.Tables[0].Rows[0]["hobbies"].ToString().Split(',');
                        cblhobbies.ClearSelection();
                        for (int i = 0; i < cblhobbies.Items.Count; i++)
                        {
                            for (int j = 0; j < arr.Length; j++)
                            {
                                if (cblhobbies.Items[i].Text == arr[j])
                                {
                                    cblhobbies.Items[i].Selected = true;
                                    break;
                                }
                            }
                        }




                        ViewState["FL"] = ds.Tables[0].Rows[0]["files"].ToString();
                        btnsave.Text = "Update";
                        ViewState["ID"] = e.CommandArgument;
                        con.Close();

                    }
                }

                else if (e.CommandName == "Del")
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("usp_emp_delete", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@empid", e.CommandArgument);
                    cmd.ExecuteNonQuery();
                    con.Close();
                    Fill_Grid();

                    }
                }
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文