[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 947
  • Last Modified:

dropdown in gridview

Hello guys,

I've been banging my head against this for while.

I have a gridview for showing products, each product has a taxation value i think it's called VAT in english, (MVA in norwegian). The different tax percents is in another table and when i edit the gridview i want the editor to be able to choose the VAT percent for the product. I have supplied the VAT values as a dropdown in edit mode. However when i update the row, the dropdown always return null. and i can't find where the problem is.

here is the code for the gridview.

Thanks for any help.

<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
        DataSourceID="sdsBusinessProduct" OnDataBound="gvProduct_DataBound" OnRowUpdated="gvProduct_RowUpdated">
        <Columns>
            <asp:BoundField ReadOnly="True" >
                <ItemStyle Width="4%" />
            </asp:BoundField>
            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" >
                <HeaderStyle HorizontalAlign="Left" />
            </asp:BoundField>
            <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" >
                <HeaderStyle HorizontalAlign="Left" />
            </asp:BoundField>
            <asp:TemplateField HeaderText="MVAID" InsertVisible="False" SortExpression="MVAID">
                <EditItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
                        DataSourceID="sdsBusinessMva" DataTextField="Description" DataValueField="MVAID" SelectedValue='<%# Bind("MVAID") %>'>
                    </asp:DropDownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("MDescription") %>'></asp:Label>
                </ItemTemplate>
                <HeaderStyle HorizontalAlign="Left" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Endre" ShowHeader="False">
                <EditItemTemplate>
                    <asp:ImageButton ID="imgUpdate" runat="server" CausesValidation="True" CommandName="Update"
                        Text="" />&nbsp;<asp:ImageButton ID="imgCancel" runat="server" CausesValidation="False"
                            CommandName="Cancel" Text="Cancel" />
                </EditItemTemplate>
                <ItemStyle HorizontalAlign="Center" />
                <ItemTemplate>
                    &nbsp;<asp:ImageButton ID="imgNew" runat="server" CausesValidation="False" OnClick="imgNew_Click"
                        Text="" />&nbsp;<asp:ImageButton ID="imgEdit" runat="server" CausesValidation="False"
                            CommandName="Edit" Text="Edit" />
                    <asp:ImageButton ID="imgDelete" runat="server" CausesValidation="False" CommandName="Delete"
                        Text="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField ReadOnly="True" >
                <ItemStyle Width="4%" />
            </asp:BoundField>
        </Columns>
    </asp:GridView>
0
oslonet
Asked:
oslonet
1 Solution
 
MatrimCommented:
For the asp.net page this example adds a ddl

  <asp:DropDownList id="ddlDiscontinued" DataSource="<%# BindTheDiscontinued() %>" OnPreRender="SetDropDownIndex" DataTextField="Discontinued" DataValueField="Discontinued" runat="server" />

background C# required is

string strDiscontinued;

GetData obj;

string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn ="server=localhost;uid=sa;pwd=;database=northwind";
if (!Page.IsPostBack )
{
BindGrid();
}
}


//To Bind the DataGrid
void BindGrid()
{
     obj=new GetData ();
     strSql = "Select productid, discontinued from Products";
     ds=obj.GetDataFromTable (strSql ,strConn);
     DataGrid1.DataSource =ds;
     DataGrid1.DataBind ();
}

//To display Yes/No for True/False
protected string ShowVal(bool blnval)
{
     if (blnval==true)
     {
          return "Yes";
     }
     else
     {
          return "No";
     }
}

//Bind the Data to the dropdownlist in the EditTemplate
protected SqlDataReader BindTheDiscontinued()
{
     obj=new GetData ();
     strSql ="SELECT distinct 'Discontinued' =" ;
     strSql+=" CASE ";
     strSql+=" WHEN Discontinued = 1 Then 'Yes'" ;
     strSql+=" ELSE 'No'" ;
     strSql+=" END " ;
     strSql+=" From Products ";
     dr=obj.GetSingleDataUsingReader (strSql ,strConn);
     return dr;
}


//Set the Text of the Dropdownlist to the field value in Database

protected void SetDropDownIndex(Object sender ,System.EventArgs e )
{
     DropDownList ed ;
     ed = (DropDownList) sender;
     ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}

 
//For Edit Update Cancel
 public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
 {
      strDiscontinued = ((Label )e.Item.FindControl("lblDiscontinued")).Text;
      DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
      BindGrid();
 }
 
 public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)
 {
      DropDownList TempList ;
      String TempValue ;
      TempList = (DropDownList) e.Item.FindControl("ddlDiscontinued");
      TempValue = TempList.SelectedItem.Value;
       //Place update code here
      Response.Write (TempValue);
      DataGrid1.EditItemIndex = -1;
      BindGrid();
 }
 public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
 {
      DataGrid1.EditItemIndex = -1;
      BindGrid();
 }
 
 
 
 //Functions used in Class GetData.cs
 
 SqlConnection mycn;
 SqlDataAdapter myda;
 SqlCommand mycmd;
 DataSet ds;
 String strConn;
 SqlDataReader myReader;
 public DataSet GetDataFromTable(string strSQL ,string strConnString)
 {
 try
 {
      strConn=strConnString;
      mycn = new SqlConnection(strConn);
      myda = new SqlDataAdapter (strSQL, mycn);
      ds= new DataSet ();
      myda.Fill (ds,"Table");
      return ds;
 }
 catch(Exception ex)
 {
      throw new Exception (ex.Message.ToString ());
 }
 finally
 {
      mycn.Close ();
 }
 }
 
 public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)
 {
 try
 {
      strConn=strConnString;
      mycn = new SqlConnection(strConn);
      mycmd = new SqlCommand (strSQL, mycn);
      mycn.Open ();
      myReader=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
      return myReader;
 }
 catch(Exception ex)
 {
      throw new Exception (ex.Message.ToString ());
 }
 finally
 {
      //mycn.Close ();
 }
 }
 


taken from syncfusion
0
 
oslonetAuthor Commented:
i'm sorry, think this is a bit extreme. I've seen people that have managad to add a dropdownlist to a gridview without any code behind. My dropdown binds the data correctly. The values and text fields are all correct, however when i press the update button, it doesn't pass the value of the dropdown, instead it passes null. I have managed to do this correctly in a detailsview, so there shouldn't be a problem to do the same in a gridview.

Thanks for the help though
0
 
renjurdevanCommented:
well your dropdown in <EditItemTemplate> tag!!

So the dropdown inside <EditItemTemplate> will get only in edit mode!! That is the reason the object become null !!

Regards
Renju
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
oslonetAuthor Commented:
i'm not sure what you mean, how can i fix this?

I want the dropdownlist to show in the edit template. It shows what option is selected, then i change it for example and press update. Then when i check it in rowupdated, i see that the newvalue called MVAID is null. while the values of the textboxes are set.
0
 
oslonetAuthor Commented:
I've located the problem. i add an extra header to the gridview, somehow this messes it up. the code for adding the header is as following:

dsText = new DataSetTextClass(sessionID);
        if(GridView1.HasControls() == true){
       
            // Defines controls
            GridViewRow HeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
            TableCell cell1 = new TableCell();
            TableCell cell2 = new TableCell();
            Label l = new Label();
            Table tbl = (Table)GridView1.Controls[0];
            TableCell[] cells = new TableCell[2];

            // set row style
            HeaderRow.CssClass = "Header2";

            // sets first cell (Label)
            l.Text = dsText.GetText(GridviewHeader);
            cell1.Controls.Add(l);
            cell1.ColumnSpan = Convert.ToInt16(GridView1.Rows[0].Cells.Count / 2);
            cell1.Style.Add("padding-left", "4%");
            cells[0] = cell1;

            // sets second cell (extra functions; excel, print, help etc)
            // printing imghelp with tooltip
            if (Help)
            {
                Image imgHelp = new Image();
                imgHelp.ImageUrl = imgURL + "icons/help.gif";
                imgHelp.ToolTip = dsText.GetText(HelpText);
                cell2.Controls.Add(imgHelp);
            }
            // adds print page
            if (Print) {
                ImageButton imgPrint = new ImageButton();
                imgPrint.ImageUrl = imgURL + "icons/print.gif";
                imgPrint.Attributes.Add("onclick", "window.print(); return false;");
                cell2.Controls.AddAt(1, imgPrint);
            }

            ImageButton imgExcel = new ImageButton();
            imgExcel.ImageUrl = imgURL + "icons/excel.gif";
            // imgExcel.Click +=
            cell2.Controls.AddAt(0, imgExcel);
           


            // sets style
            cell2.HorizontalAlign = HorizontalAlign.Right;
            cell2.ColumnSpan = Convert.ToInt16(GridView1.Rows[0].Cells.Count / 2 + 0.5);

            // adds cell 2
            cell2.Style.Add("padding-right", "4%");
            cells[1] = cell2;

            // Build row
            HeaderRow.Cells.AddRange(cells);

            // adds row to gridview
            tbl.Rows.AddAt(0, HeaderRow);

Can anyone tell me why this makes a problem in the gridview?
0
 
renjurdevanCommented:
Try it in RowUpdating event

DropDownList obj = (DropDownList) GridView1.Rows[e.RowIndex].Cells[0].Controls[1];

Cells and Controls may vary according to your need

Regards
Renju
0
 
oslonetAuthor Commented:
I found the sollution just now. the header has to be added in the rowcreating event, seems like when added at a later stage i messes up the headers for the databound columns in the gridview and therefore dropdownlist. I alse found out that adding an extra an extra header wont work with template fields unless you add it in a createrow event
0
 
Computer101Commented:
PAQed with no points refunded (of 500)

Computer101
EE Admin
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now