如何在ASP GridView中获取所选值的唯一ID [英] How to get the only the id of the selected value in ASP gridview

查看:183
本文介绍了如何在ASP GridView中获取所选值的唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在asp Gridview上工作,我想通过从另一个表中加入内容并显示id来获取内容的id.并且dropdownlist的id没有在后面的代码中显示.这是我的摘录

我尝试过的事情:

Hi
I am working on asp Gridview and I want to get the Id of the content by joining the content from another table and display the id.And the id od the dropdownlist is not showing in code behind.Here is my snippnet

What I have tried:

<pre>protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bind();
                Bindmachine();
            }
        }
        protected void bind()
        {
            cn.Open();
            SqlCommand cmd = new SqlCommand("Select Sample7.Empid,Sample7.EmpName,Sample6.machineid From Sample7 Join Sample6 ON Sample7.Categoryid = Sample6.machineid ", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            cn.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                gvDetails.DataSource = ds;
                gvDetails.DataBind();
            }
        }
        protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Add"))
            {
                TextBox txtEmpId = (TextBox)gvDetails.FooterRow.FindControl("txtempid");
                TextBox txtEmpName = (TextBox)gvDetails.FooterRow.FindControl("txtempname1");
                DropDownList ddlEmpDep = (DropDownList)gvDetails.FooterRow.FindControl("txtmac1");
                

                cn.Open();
                SqlCommand cmd =
                new SqlCommand(
                "insert into Sample7(EmpId,EmpName,Categoryid) values('" + txtEmpId.Text + "','" + txtEmpName.Text + "','" +
                ddlEmpDep.SelectedValue + "')", cn);
                int result = cmd.ExecuteNonQuery();
                cn.Close();
                if (result == 1)
                {
                    bind();

                }
                else
                {

                }
            }
        }


        protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int EmpId = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
            string username = gvDetails.DataKeys[e.RowIndex].Values["EmpName"].ToString();
            DropDownList txtmac = (DropDownList)gvDetails.Rows[e.RowIndex].FindControl("txtmac1");
            
            cn.Open();
            SqlCommand cmd = new SqlCommand("Update Sample7 set machineid ='" + txtmac.Text + "' where EmpId=" + EmpId, cn);
            cmd.ExecuteNonQuery();
            cn.Close();

            // lblresult.Text = username + " Details Updated successfully";
            gvDetails.EditIndex = -1;
            bind();
        }
        protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int EmpId = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["EmpId"].ToString());
            string username = gvDetails.DataKeys[e.RowIndex].Values["EmpName"].ToString();
            cn.Open();
            SqlCommand cmd = new SqlCommand("delete from Sample7 where EmpId=" + EmpId, cn);
            int result = cmd.ExecuteNonQuery();
            cn.Close();
            if (result == 1)
            {
                bind();

                
            }
        }
        protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvDetails.EditIndex = -1;
            bind();
        }
        protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvDetails.EditIndex = e.NewEditIndex;
            bind();
        }
        protected void gvDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {


        }
        protected void Bindmachine()
        {
            DataTable dt = new DataTable();
            cn.Open();
            SqlCommand cmd = new SqlCommand("Select * from Sample6", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            //DataSet ds = new DataSet();
            da.Fill(dt);
            cn.Close();
            ddlmachine.DataSource = dt;
            ddlmachine.DataTextField = "CategoryName";
            ddlmachine.DataValueField = "CategoryName";
            ddlmachine.DataBind();
            ddlmachine.Items.Insert(0, new ListItem("--Select--"));

        }

        protected void ddlmac_SelectedIndexChanged1(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cn.Open();
            if (ddlmachine.SelectedValue != "")
            {
                string[] sal = ddlmachine.SelectedValue.Split(',');
                

                SqlCommand cmd = new SqlCommand("select * from Sample7 ", cn);
                
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
            }

            else
            {
                SqlCommand cmd = new SqlCommand("select * from Sample7", cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
            }
            cn.Close();
            gvDetails.DataSource = dt;
            gvDetails.DataBind();
        }

<pre><asp:GridView ID="gvDetails" style="background-color:lightblue;     border-collapse: collapse;
               background-color: lightgreen;
    margin-top: -53px;" DataKeyNames="EmpId,EmpName" runat="server"

               HeaderStyle-CssClass="TableHead"

                AutoGenerateColumns="false"  HeaderStyle-BackColor="#61A6F8"

                ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="white"

                CellPadding="10" CellSpacing="0"

                AllowPaging="true" PageSize="5"

                OnRowCommand="gvDetails_RowCommand"  OnRowUpdating="gvDetails_RowUpdating" 

                OnRowEditing="gvDetails_RowEditing" OnRowCancelingEdit="gvDetails_RowCancelingEdit"

                OnRowDeleting="gvDetails_RowDeleting" OnPageIndexChanging="OnPaging"

                 AllowSorting="True" OnRowDataBound="gvDetails_OnRowDataBound"

                OnTextChanged="OnTextChanged">

        <Columns >
                    <asp:TemplateField  HeaderText="EmployeeID">
                        <ItemTemplate>
                            <asp:Label ID="lblempid" runat="server" 

                                Text='<%# Eval("EmpId")%>'></asp:Label>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtempid" 

                                MaxLength="5" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="rfvempid" runat="server" ControlToValidate="txtempid" Text="*" ValidationGroup="validaiton" />
                        </FooterTemplate>
                    </asp:TemplateField>



                    <asp:TemplateField HeaderText="EmployeeName">
                        <HeaderTemplate>
                            EmployeeName 
                             <br></br>
                            
                            

                        </HeaderTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtempname" runat="server"   Text='<%#Eval("EmpName") %>' />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblempname" runat="server"  Text='<%#Eval("EmpName") %>' />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtempname1" runat="server"  AutoPostBack="false"  />
                            <asp:RequiredFieldValidator ID="rfvempname" runat="server" ControlToValidate="txtempname1" Text="*" ValidationGroup="validaiton" />
                        </FooterTemplate>
                    </asp:TemplateField>


                    <asp:TemplateField HeaderText="Categoryid">
                        <HeaderTemplate>
                            Categoryid 
                             <br></br>
                            
                            

                        </HeaderTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlmachine" runat="server" OnSelectedIndexChanged="ddlmac_SelectedIndexChanged1" ></asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblmac" runat="server"  Text='<%#Eval("machineid") %>' />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="txtmac1" runat="server" />
                            <asp:RequiredFieldValidator ID="rfvdep" runat="server" ControlToValidate="txtmac1" Text="*" ValidationGroup="validaiton" />
                        </FooterTemplate>
                    </asp:TemplateField>

            <asp:TemplateField HeaderText="Edit/Delete" HeaderStyle-Width="5%">
                        <EditItemTemplate>
                            <asp:ImageButton ID="imgbtnUpdate"  CommandName="Update" runat="server" ImageUrl="~/Images/update.png" ToolTip="Update" Height="20px" Width="20px" />
                            <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/cancel.png" ToolTip="Cancel" Height="20px" Width="20px" />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/ediit.png" ToolTip="Edit" Height="20px" Width="20px" />
                            <asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/deletee.png" ToolTip="Delete" Height="10px" Width="10px" />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/Add.png" CommandName="Add" Width="20px" Height="20px" ToolTip="Add new User" ValidationGroup="validaiton" OnClientClick="GetGridFooterRowvalues()" />
                        </FooterTemplate>
                    </asp:TemplateField>

                   
                </Columns>
        </asp:GridView>

Create Table Sample7 (id int identity(1,1),Empid int,EmpName varchar(50),Categoryid nvarchar(50))

Insert Into Sample7 (Empid,EmpName,Categoryid)
Values (1,'Rahul','1'),
 (2,'Sam','2'),(3,'Raj','3')
Select * from Sample7

Create Table Sample6 (id int identity(1,1),machineid nvarchar(50) ,CategoryName varchar(50))
Insert Into Sample6 (machineid,CategoryName)
Values (1,'Machine1'),(2,'Machine2'),(3,'Machine3')
Select * from Sample6

Select Sample7.Empid,Sample7.EmpName,Sample6.machineid From Sample7
Join Sample6 ON Sample7.Categoryid = Sample6.machineid

推荐答案

You will have to use machineid to get the value as id on selection
You will have to use machineid to get the value as id on selection
ddlmachine.DataValueField = "machineid";


protected void Bindmachine()
{
DataTable dt = new DataTable();
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from Sample6", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataSet ds = new DataSet();
da.Fill(dt);
cn.Close();
ddlmachine.DataSource = dt;
ddlmachine.DataTextField = "CategoryName";
ddlmachine.DataValueField = "CategoryID"; //"CategoryName"; Here the column name which contains the ID should bind.
ddlmachine.DataBind();
ddlmachine.Items.Insert(0, new ListItem("--Select--"));

}
Check this code it may help you.
protected void Bindmachine()
{
DataTable dt = new DataTable();
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from Sample6", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataSet ds = new DataSet();
da.Fill(dt);
cn.Close();
ddlmachine.DataSource = dt;
ddlmachine.DataTextField = "CategoryName";
ddlmachine.DataValueField = "CategoryID"; //"CategoryName"; Here the column name which contains the ID should bind.
ddlmachine.DataBind();
ddlmachine.Items.Insert(0, new ListItem("--Select--"));

}
Check this code it may help you.


这篇关于如何在ASP GridView中获取所选值的唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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