how to populate a dropdownlist control and update the selected item in a gridview control

Hi friends

help me with this ...

Requirement:

1) i want to populate a dropdownlist(ddl) in a gridview when clicking the edit button of a perticular row by using gridview events and also update the selected item of the ddl to the database.

2) also i don't want to use sqldatasource controls i.e. we should take the help of only gridview events

3) DropDownList will be populated fom TableB:

Actions taken:

In page_load while binding the grid i m getting the error:

Cannot perform '=' operation on System.Int32 and System.String

 my fields and datatypes are as follows in TableA

field name:   datatype in db column:

PatientId:          bigint              

forename         varchar(35)

salutation        varchar(35)

i knowingly commented some code only for testing purpose 

please guide me through this and reply what code i should add or remove.

if u have any links which can be helpful to me then plz post the link.

All suggestions and feedbacks are highly welcomed.

 

aspx page:

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

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

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Style="position: static;" Width="513px" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound">
            <headerstyle backcolor="DarkSlateGray"
         forecolor="Khaki" font-bold="True" />

            <Columns>
                <asp:BoundField DataField="patientid" HeaderText="PatientId" ReadOnly="True" />
                <asp:TemplateField HeaderText="Name">
                <itemtemplate>
                <asp:label runat="server" id="lblName" text='<%# Eval ( "forename" ) %>' />
                </itemtemplate>

                <edititemtemplate>
                    <asp:textbox runat="server" id="txtname" width="69%" text='<%# Bind ( "forename" ) %>' Height="18px" style="position: static" />
                </edititemtemplate>
                    <FooterTemplate>
                        &nbsp;
                    </FooterTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="salutation">
                    <ItemTemplate>
                        <asp:Label ID="lblSaluation" runat="server" Style="position: static" text='<%# Eval ( "Salutation" ) %>'
                            Width="71px"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlSaluation" runat="server" Style="position: static" Width="104px">
                           
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <%--
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlSaluation" runat="server" Style="position: static" Width="104px"
                            DataSource='<%# BindSalutation() %>' DataTextField="SalutationType" DataValueField="SalutationType" SelectedValue='<%# Bind("SalutationType") %>' >
                        </asp:DropDownList>
                    </EditItemTemplate>
                    --%>
                   
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
               
            </Columns>
        </asp:GridView>
       </div>
    </form>
</body>
</html>

codefile:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace grid1
{
    public partial class GridViewHashmat : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
            }

        }


        public void BindGrid()
        {
            try
            {
                string ConnectionString = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
                SqlConnection myCon = new SqlConnection(ConnectionString);
                myCon.Open();
                SqlCommand myCmd = (SqlCommand)myCon.CreateCommand();
                myCmd.CommandType = CommandType.Text;
                string strsql = "Select patientid,forename,salutation from TableA";
                myCmd.CommandText = strsql;
                SqlDataAdapter da = new SqlDataAdapter(myCmd);
                DataSet ds = new DataSet();
                da.Fill(ds, "MyTable");
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
                string strException = ex.Message.ToString();
            }

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGrid();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindGrid();

        }
       /* public void BindSalutation()
        {
            string ConnectionString = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
            SqlConnection myCon = new SqlConnection(ConnectionString);
            myCon.Open();
            SqlCommand myCmd = (SqlCommand)myCon.CreateCommand();
            myCmd.CommandType = CommandType.Text;
            string strsql = "Select SalutationType from title";
            myCmd.CommandText = strsql;
            myCmd.ExecuteReader(CommandBehavior.CloseConnection);
            return;

        }*/
     
      
      /*  public void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int patientid;
            string name;
          
            patientid = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
            name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            string saluation = ((DropDownList)ddl).SelectedItem.Value.ToString();

            string ConnectionString = ConfigurationManager.ConnectionStrings["KCPCT_SMARTCareConnectionString"].ConnectionString;
            SqlConnection myCon = new SqlConnection(ConnectionString);
            myCon.Open();
            SqlCommand cmd = new SqlCommand("update TableA set Forename=@name,saluation=@saluation where patientid=@patientid");
            cmd.Parameters.Add(new SqlParameter("@name", name));
            cmd.Parameters.Add(new SqlParameter("@saluation", saluation));
            cmd.Parameters.Add(new SqlParameter("@patientid",patientid));
            cmd.ExecuteNonQuery();
            myCon.Close();

            GridView1.EditIndex = -1;
            BindGrid();

        }*/
        private DataSet getdataset()
        {
            string connectionstring = ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
            string query = "select SalutationType from TableB";
            SqlConnection myconnection = new SqlConnection(connectionstring);
            myconnection.Open();
            SqlDataAdapter ad = new SqlDataAdapter(query, myconnection);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            return ds;
           
        }


         protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
         {
             DataTable mytable = new DataTable();
             DataColumn SalutationType = new DataColumn("SalutationType");

             mytable.Columns.Add(SalutationType);

             DataSet ds = new DataSet();
             ds = getdataset();
             string expression = String.Empty;


             if (e.Row.RowType == DataControlRowType.DataRow)
             {
                 string SalutationType= Convert.ToString(e.Row.Cells[0].Text);

                 expression = "SalutationType = " + SalutationType;
                 DropDownList ddl = (DropDownList)e.Row.FindControl("dropdownlist1");
                 DataRow[] rows = ds.Tables[0].Select(expression);


                 foreach (DataRow row in rows)
                 {
                     DataRow newrow = mytable.NewRow();
                     newrow["SalutationType"] = row["SalutationType"];
                     mytable.Rows.Add(newrow);
                 }
                 ddl.DataSource = ds;
                 ddl.DataTextField ="SalutationType";
                 ddl.DataValueField = "SalutationType";
                 ddl.DataBind();
             }

         }

    }
}

 

0
i_m_hashmat
10/15/2008 7:59:21 AM
asp.net.object-datasource 16182 articles. 0 followers. Follow

1 Replies
1327 Views

Similar Articles

[PageSpeed] 29

Hi

I have doubt in code written in GridView1_RowDataBound

There you have written

ddl.DataSource = ds;
ddl.DataTextField ="Salutation";
ddl.DataValueField = "Salutation";
ddl.DataBind();

But your ds doesn't contain Salutation it contains SalutationType instead.


Thanks & Regards,

Omkar A. Lale

"Courage is what it takes to stand up and speak; courage is also what it takes to sit down and listen."

~ Do Mark as Answer if it solves your query ~
0
Omkar
10/15/2008 12:15:17 PM
Reply:

Similar Artilces:

Problem in Using DropDownList Control to select a selected row of SqlDataSource that is under GridView Control
Hi all,In my SQL Server Management Studio Express, I have a database "ChemDatabase" that has a table "LabData"  formatted in the following way: SampleID int PRIMARY KEY, SampleName nvarchar(25), ChemicalName, nvarchar(25), Concentration decimal(6.2) with 5 rows of records in this .dbo table. In my Visual Web Developer Express, I created a website "RPD-TCE" for extracting a row of record from the LabData table by using a DropDownList, a GridView and a SqlDataSource.  I want to click DropDownList to list one number of S...

How to display the more than one row with items and buttons in gridview control. when i select three items at same time from categories(Fruits, Apples, Gifts). The selected items are displayed in g
Hi,when i select three items at same time from categories(Fruits, Apples, Gifts). The selected items are displayed in gridview.Here i would like to change this way "when i click more than one category at same time. it should be display selected item and button."For example: if i have to select Fruits, Apples from categories.  it should be display like 1st "row have Fruits and In 2nd row have Apples and button" in gridview.the button have some event.How can i do it? Please can anyone answer me.With kind requestThanks your query is very raw..can u details it out...Pl...

Custom Datasource Controls Vs. Object Datasource Controls
Hi folks,I am a web developer developing pages in the project. I need to integrate the front end pages with the backend API. Active directory is being used as the database system for our project. I only use the API and the methods offered by it to interact with the data.For all the operations on the data, I have methods that I can call from the API (viz. Create(), Delete(), Modify() etc.). For connecting the data to my frontend data controls (viz. GridView, DropDownList etc.) I can use Object Datasource Control. I also read some articles about Custom Datasource controls. Now, I am having a d...

Menu Control in side item templete in side GridView insdie Update Panel error = 0.cells is null or not an object
Dear Team i am unsing ASP.NET 2.0 JavaScript C# Ajaxi am having an updatepanel and in side it i have a gridview with an item templete MenuControl, this menu when i click on any item it open a new popup when i close it and try to use the menu again i have a javascript error, 0.cells is null or not an objectplease advise what to do it is more than urgent. thank you...

Menu Control in side item templete in side GridView insdie Update Panel error = 0.cells is null or not an object
Dear Team i am unsing ASP.NET 2.0 JavaScript C# Ajaxi am having an updatepanel and in side it i have a gridview with an item templete MenuControl, this menu when i click on any item it open a new popup when i close it and try to use the menu again i have a javascript error, 0.cells is null or not an objectplease advise what to do it is more than urgent. thank you...

Responding to selected control items in Datalist control
 Hi ladies and gentlemen . I am having a kinda wierd problem. I am using a datalist control bound to a database and I have implamented the following code.              <asp:DataList ID="MainCategory" runat="server" SelectedIndex="1" style="line-height: normal; text-align: left" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Left" RepeatColumns="3" ShowFooter="False" ShowHeader="False" Width="335px"  Font-Size="Medium" Height="58px" OnItemComman...

Cannot access a dropdownlist control inside the gridview control
I am using the Gridview control without a DataSource control. When I click on the Edit button, the page posts back and enters the following code: <code>     Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing         Try            Dim row As GridViewRow = GridView1.Rows(e.NewEditIndex)            Dim ddlCustomerID As DropDownList...

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one colum.now my question is i need another gridview to be placed in the  first gidviewso that when i click on the button the second gridview will populate the data.now my question is how to place second gridview in first gridview.or is there any approach like first grid itself acting as parent and child.please help me  Hi sirikalavalapalli:                I think nested gridview will help you. Check this link and it will show you how...

Gridview control for selecting items
Is there a control that can move selected items from one GridView to another? In the first GridView the selected item has to dissappear and appear in the second grid.Johan TheunissenMCPD, MCSE, MCTS BizTalk 2006==============================Please mark the most helpful reply/replies as "Answer". First you must add the SELECT CommandField in your GridView.. then you can have it this way    protected void Button1_Click(object sender, EventArgs e)    {               for (int i ...

When to select items in a dropdownlist control?
I have a DropDownList that loads its data from a SqlDataSource. Right after the data has been loaded into the DropDownList, I want to programmaticaly go in and make a selection based a QueryString ID. So the question is, when do I start executing my code to make selection of the DropDownList items? After you are done with loading the dropdownlist with data from the database.Thanks,MaxLet Me Google That For You! I know that, but where exactly is the event handler or method that I will need to put my code in? So you don't load it programatically. If thats the case, did you try Page_LoadT...

Updating and binding control to other controls within the same row of a GridView
HiIn the EditTemplate of my GridView I show 2 DropDownLists. When the user selects the first dropdownlist, I need it to update the contents of the second dropdownlist. I have my Subs that do this fine when not inside the GridView, but what is the correct way to do it whilst they are in the GridView?This is my current attempt that returns the error 'Object reference not set to an instance of an object'. I presume its related to correctly targeting the DropDownList in question? This is my GridView:<asp:GridView ID="GridView1" runat="server"  &...

How to dynamically populate a dropdownlist control in a InsertItemTemplate of DetailView control.
Guys,I have a very basic problem. I have two dropdownlist in InsertItemTemplate of a Detailview Control for Category and Subcategory. I am getting list of catetories and subcategories in respective dropdown list. Now i want to populate Subcategory dropdownlist based on the Value selected in the Category Dropdownlist. How can i pass CategoryID as parameter value for subcategory dropdownlist control at runtime? I can't see the Category dropdownlist contol name in the Databinding and popup comes to choose parameter. Any suggestions? Thanks in advance.   Positive attit...

Populating a control in client side on selection of another control
Hey,  i am facing a problem. I need to populate one drop down with all state values depending on the selection of Country in country drop down in my aspx page. Can u suggest me how i can handle the situation in client side, since the server side code involves so many post back. I prefer in javascript.   Thanks if document.getelementbyid('lst').options[1].selected { fill ur second list here...... }Vijay MannSoftware Developer Noida India...

Getting the control id of a control inside gridview control
 uhmm.. a little bit confusing regarding my subject because i dont know how to say it...by the way my problem is how can i get the id of a control (e.g. textbox) inside the gridview... and the textbox is in the templatefield... is there any way i can get its id??  hoping i could get a reply as soon as possible... Regards,MhaeyPlease remember to click “Mark as Answer” on the post that helps you.. =) What do you want's to do by getting the id of the Text box? Do you want's to find particular Textbox with certain id ? Kamran ShahidSr. Software Engineer(MCP,MCAD.net,MC...

Web resources about - how to populate a dropdownlist control and update the selected item in a gridview control - asp.net.object-datasource

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 11/26/2015 9:43:44 PM