Binding Drop down in grid view programatically - c#

<asp:GridView ID="gvStates" AutoGenerateColumns="false" Width="100%" AllowSorting="true"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<HeaderStyle BackColor="#57768f" ForeColor="White" />
<RowStyle BackColor="#dae2e8" ForeColor="Black" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#ffffff" ForeColor="Black" />
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlSess" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Scheduled">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Bind("Sched")%>' />
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="_b_SchStat" runat="server" AutoPostBack="true" Text="UnSchedule" OnClick="_b_ToggleSched" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Recruiter">
<ItemTemplate>
<asp:DropDownList ID="ddRec" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddR">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
[dbo].[QRY_RecruitGrid]
#jobnum varchar(20),
#quota varchar(10),
#sess VARCHAR(10)
AS
SELECT
[job_resp_recordid] as 'key'
,[job_resp_name] as 'Name'
,[job_resp_quota] as 'Quota'
,[job_resp_session] as 'Sess'
,[job_resp_scheduled] as 'Sched'
,COALESCE([job_resp_recruited_by], '') as 'Recruiter'
,case when len(ltrim(rtrim([job_resp_phone])))='10' then '('+SUBSTRING([job_resp_phone],1,3)+')'+' '+SUBSTRING([job_resp_phone],4,3)+'-'+SUBSTRING([job_resp_phone],7,4) when len(ltrim(rtrim([job_resp_phone])))='' then ' ' end AS [MN Phone]
,case when len(ltrim(rtrim([job_resp_cellphone])))='10' then '('+SUBSTRING([job_resp_cellphone],1,3)+')'+' '+SUBSTRING([job_resp_cellphone],4,3)+'-'+SUBSTRING([job_resp_cellphone],7,4) when len(ltrim(rtrim([job_resp_cellphone])))='' then ' ' end AS [Cell Phone]
FROM [dbo].[tbl_job_respondents]
WHERE job_resp_job_number like #jobnum
and job_resp_quota like #quota
AND job_resp_session LIKE #sess
order by job_resp_quota, [job_resp_name]
I'm trying to bind the 'ddRec' dropdown to the Recruiter field in the dataset. I tried
DataTextField='<%#Bind("Recruiter")%>'
Edit:
Error: {"Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."}
Let me explain better sorry. I'm trying to set the value from the proc but the dropdown list itself is being populated from a query on the OnRowCreated Event I think this is my problem
protected void gvStates_RowCreated(object sender, GridViewRowEventArgs e)
{
var drop = new List<string> { "" };
var LNQ = new LNQDataContext();
var Rec = LNQ.Recruits.Where(c => c.Active == "Y").Select(c => new { c.Name });
var Rdp = new List<string> { "" };
foreach (var a in Rec) { Rdp.Add(a.Name); }
for (int i = 1; i <= _cnt; i++) { drop.Add("S" + i); }
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = (DropDownList)e.Row.FindControl("ddlSess");
ddl.DataSource = drop;
ddl.DataBind();
var ddR = (DropDownList)e.Row.FindControl("ddRec");
ddR.DataSource = Rdp;
ddR.DataBind();
}
}

You can't programmatically bind to the DataTextField field; the DataTextField identifies the field to display in the drop down, hence it has to be static and is not evaluated per row. Though, you can tap into the Grid's RowDataBound event, and programmably set the DataTextField property and bind data at that point.
HTH.

Related

How to get the selected value of a dropdownlist in a Gridview C#

I'm having a GridView to display few columns. when I click the edit button in the GridView, it displays a DropDownList for one column which has a list of values to select.
I need to select a value and click on the Update button to update the database with the latest selected value.
<asp:GridView ID="GrdAttributesView" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CssClass="well"
EmptyDataText="No Records to display."
OnPageIndexChanging="GrdAttributesView_PageIndexChanging"
OnRowCancelingEdit="GrdAttributesView_RowCancelingEdit"
OnRowEditing="GrdAttributesView_RowEditing"
OnRowUpdated="GrdAttributesView_RowUpdated"
OnRowUpdating="GrdAttributesView_RowUpdating"
OnSelectedIndexChanged="GrdAttributesView_SelectedIndexChanged"
OnSorting="GrdAttributesView_Sorting"
OnRowDeleting="GrdAttributesView_RowDeleting"
OnRowDeleted="GrdAttributesView_RowDeleted"
OnRowDataBound="GrdAttributesView_RowDataBound" PagerSettings-Mode="Numeric"
PagerStyle-Font-Bold="true" PageSize="20" ShowHeaderWhenEmpty="True">
<Columns>
<%-- <asp:TemplateField HeaderText="Globalized Indicator">
<ItemTemplate>
<asp:CheckBox ID="Chk_GlobalizedIndicatorGrid" runat="server" Width="55px" OnCheckedChanged="Chk_GlobalizedIndicatorGrid_CheckedChanged" Text='<%# Eval("GlobalizedInd") %>' Checked ='<%# Eval("GlobalizedInd") == DBNull.Value ? false : Convert.ToBoolean(Eval("GlobalizedInd")) %>' Enabled="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:CommandField HeaderText="Edit Record" ItemStyle-Width="150px" ShowEditButton="True" ShowHeader="True" ShowDeleteButton="true">
<ItemStyle Width="100px" />
</asp:CommandField>
<asp:BoundField HeaderText="Added Date" DataField="AddedDate" ItemStyle-Width="700px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="200px"></ControlStyle>
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Created By" DataField="CreatedBy" ItemStyle-Width="700px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="100px"></ControlStyle>
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Ticket Number" DataField="TicketNumber" ItemStyle-Width="200px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="200px"></ControlStyle>
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Ticket URL" DataField="TIcketURL" ItemStyle-Width="200px" ReadOnly="true" ControlStyle-Width="700px">
<ControlStyle Width="600px"></ControlStyle>
<ItemStyle Width="600px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Hours Spent" ItemStyle-Width="100px" ControlStyle-Width="700px">
<ControlStyle Width="100px"></ControlStyle>
<ItemStyle Width="100px"></ItemStyle>
<ItemTemplate>
<asp:Label ID="LblHoursSpent" runat="server" Text='<%# Eval("HoursSpent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblHoursSpent" runat="server" Text='<%# Eval("HoursSpent")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="CmbHoursSpent" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Minutes Spent" ItemStyle-Width="100px" ControlStyle-Width="700px">
<ControlStyle Width="120px"></ControlStyle>
<ItemStyle Width="120px"></ItemStyle>
<ItemTemplate>
<asp:Label ID="LblMinutesSpent" runat="server" Text='<%# Eval("MinutesSpent")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="LblMinutesSpent" runat="server" Text='<%# Eval("MinutesSpent")%>' Visible="false"></asp:Label>
<%--<asp:DropDownList ID="CmbHoursSpent" AppendDataBoundItems="true" DataTextField="NumberofHoursSpent" DataValueField="HoursSpent" AutoPostBack="false" runat="server" OnSelectedIndexChanged="CmbHoursSpent_SelectedIndexChanged" enabled="true">
</asp:DropDownList>--%>
<asp:DropDownList ID="CmbMinutesSpent" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle Font-Bold="True" />
</asp:GridView>
The code behind is as follows:
protected void GrdAttributesView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GrdAttributesView.EditIndex == e.Row.RowIndex)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlHours = (DropDownList)e.Row.FindControl("CmbHoursSpent");
ddlHours.DataSource = GenerateHoursList();
ddlHours.DataTextField = "NumberofHoursSpent";
ddlHours.DataValueField = "HoursSpent";
ddlHours.DataBind();
ddlHours.Items.FindByValue((e.Row.FindControl("LblHoursSpent") as Label).Text).Selected = true;
DropDownList ddlMinutes = (DropDownList)e.Row.FindControl("CmbMinutesSpent");
ddlMinutes.DataSource = GenerateMinutesList();
ddlMinutes.DataTextField = "NumberofMinutesSpent";
ddlMinutes.DataValueField = "MinutesSpent";
ddlMinutes.DataBind();
ddlMinutes.Items.FindByValue((e.Row.FindControl("LblMinutesSpent") as Label).Text).Selected = true;
}
}}
protected void GrdAttributesView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlprice = (DropDownList)GrdAttributesView.Rows[e.RowIndex].FindControl("CmbHoursSpent");
String value = ddlprice.SelectedValue;
string MinutesSpent = (GrdAttributesView.Rows[e.RowIndex].FindControl("CmbMinutesSpent") as DropDownList).SelectedItem.Value;
}
Ideally in the RowUpdating method I should get the new value from the DropDown. but I don't understand why it gives the old value even though I select a different value.
I did a lot of reading and I saw different people using the same approach to get it done. But somehow it is not working for me.
Can someone help please?

asp.net C# Gridview nested gridview

Dear all genius please help me with this had been trying everywhere but no luck. I am trying to open my nested gridview for a single Parent Row but gets open the entire parent row with one single record of the child row. It should be when I click the button of the Parent gridview row then the record for the particular row should display in the Child gridview in the same Parent row, but in my case the record of the Parent row shows up and the Child gridview gets open in all the parent row. Please need in help :(
enter image description here
<asp:GridView runat="server" ID="GridView4" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="UId" class="" CellPadding="4" PageSize="5">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="File Type" Visible="false">
<ItemTemplate>
<asp:Label ID="lblFileType" runat="server" Text='<%# Eval("FileType") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Image Name" Visible="false">
<ItemTemplate>
<asp:Label ID="lblImageName" runat="server" Text='<%# Eval("ImageName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="Image2" class="img1" runat="server" ImageUrl='<%# Bind("pic") %>' OnCommand="blah_Command" CommandName='<%# Eval("UId") %>' CommandArgument='<%# Eval("pic") %>' />
<asp:Panel ID="pnlOrders" runat="server" Style="position: relative" Visible="false">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="FileSize" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="ShareByUserId" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#ffffff" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Code Behind:
protected void blah_Command(object sender, CommandEventArgs e)
{
foreach (GridViewRow row2 in GridView4.Rows)
{
row2.FindControl("pnlOrders").Visible = true;
string customerId = e.CommandName.ToString();
GridView gvOrders = row2.FindControl("gvOrders") as GridView;
BindOrders(customerId, gvOrders);
}
}
private void BindOrders(string customerId, GridView gvOrders)
{
gvOrders.ToolTip = customerId;
gvOrders.DataSource = GetData(string.Format("select * from SShare where UId='{0}'", customerId));
gvOrders.DataBind();
}
You are looping all the rows in GridView4, so every nested GridView will be filled with data.
What you need is the row number of the row that the clicked LinkButton is in, and use that to find the nested GridView.
protected void blah_Command(object sender, CommandEventArgs e)
{
//get the current datagrid item from the sender
GridViewRow row = (GridViewRow)(((Control)sender).NamingContainer);
//the row index of the gridviewrow
int rowIndex = row.RowIndex;
//find the correct nested grid using the row index
GridView gvOrders = GridView4.Rows[rowIndex].FindControl("gvOrders") as GridView;
}

I needed to move row from a gridview to a database table How to?

everyone. I needed your help. I am creating an online workshop registration system. I have a inicale gridview that show the all the available workshop for registration during the festival time. I am using a session and check box to get the workshop that the person want into the "shopping cart" on the next page. what I needed to do is after righting a incial order written to an order table in my SQL database. What I am having issues with is when it write the registration data that is stored in an other gridview for the shopping cart. I am writing each row as a new entry into a order detail table. when I do this the program does something very odd. It seem to write all the data from the a gridview that holds all the workshop information on the first page.
code for writing the shopping cart row to the order detail table:
protected void btn_Submit_Click1(object sender, EventArgs e)
{
foreach (GridViewRow row in Basket.Rows)
{
Label lblCatCode = (Label)row.FindControl("lblCatCode");
Label lblTitle = (Label)row.FindControl("lblTitle");
SqlConnection conBasket = new SqlConnection("Data Source=JONS\\SQLEXPRESS;Initial Catalog=OFFFV2;Integrated Security=True");
SqlCommand cmdBasket = new SqlCommand("Insert into OrderDetail(OrderID,CatalogeCode,Title)Values(#OrderID,#CatCode,#Title)", conBasket);
cmdBasket.Parameters.AddWithValue("#OrderID", lblOrderNumber.Text);
cmdBasket.Parameters.AddWithValue("#CatCode", lblCatCode.Text);
cmdBasket.Parameters.AddWithValue("#Title", lblTitle.Text);
try
{
conBasket.Open();
cmdBasket.ExecuteNonQuery();
conBasket.Close();
}
catch (Exception ex)
{
lbl_Error.Text = "A database error has orrued. <br <br />" + "Message: " + ex.Message;
}
}
}
Here is the code for the gridview
<asp:GridView ID="Basket" runat="server" AutoGenerateColumns="False" DataKeyNames="WorkshopID" DataSourceID="BasketData" EnableViewState="False" ShowFooter="True" OnRowCreated="Basket_RowCreate" CellPadding="4" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:CheckBox ID="cb_BasketRemove" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cataloge Code" SortExpression="CatalogeCode">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("CatalogeCode") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCatCode" runat="server" Text='<%# Eval("CatalogeCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<strong>
Total Price:
</strong>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<ItemTemplate>
<asp:Label ID="Price" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<strong>
<asp:Literal ID="TotalPrice" runat ="server" />
</strong>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
I understand that my last post was unclear and was closed. I am at a loss as why the program is doing what it is doing. I am wondering if it is in connection with the way I get the data from the first gridview to the shopping cart.
Here is the code for the session for the selected row
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btt_Select_Click(object sender, EventArgs e)
{
var selectedWorkshop = GridView1.Rows.Cast<GridViewRow>().Where(row => ((CheckBox)row.FindControl("RegisteredWorkshop")).Checked).Select(row => GridView1.DataKeys[row.RowIndex].Value.ToString()).ToList();
if (Session["cart"] == null)
{
Session["cart"] = selectedWorkshop;
}
else
{
var cart = (List<string>)Session["cart"];
foreach (var workshop in selectedWorkshop)
cart.Add(workshop);
Session["cart"] = cart;
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("RegisteredWorkshop");
if (cb.Checked)
cb.Checked = false;
}
}
protected void btt_CheckOut_Click(object sender, EventArgs e)
{
if (Session["cart"] != null)
Response.Redirect("Checkout.aspx");
}
}
The code for the select gridview from where the registrant select from the various workshops:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource3" CellPadding="4" DataKeyNames="WorkshopID" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText ="Register">
<ItemTemplate>
<asp:CheckBox ID="RegisteredWorkshop" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FestivalYear" HeaderText="Festival Year" />
<asp:BoundField DataField="CatalogeCode" HeaderText="Catalog Code" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="WSDescription" HeaderText="Workshop Description" />
<asp:BoundField DataField="DayOffered" HeaderText="Day Offered" />
<asp:BoundField DataField="Lenght" HeaderText="Workshop Lenght" />
<asp:BoundField DataField="BeginingTime" HeaderText="Start Time" />
<asp:BoundField DataField="Price" HeaderText="Workshop Fee" />
<asp:BoundField DataField="WorkshopID" HeaderText="Workshop Id" Visible="False" />
</Columns>
I may be wrong but it looks like your variable naming is off (confusing basket and cart?).
You might need to do something like this:
protected void btn_Submit_Click1(object sender, EventArgs e)
{
var Basket = (List<string>)Session["cart"]; // ADD THIS LINE
foreach (GridViewRow row in Basket.Rows)
{

Getting value of a cell from a GridView on SelectedIndexChanged event of DropDownList

I have a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}

Sorting and paging GridView issues

i'm using a GridView and trying to sort and page it.
I have more than 20 rows on my DataBase, but the GridView just shows 10.
I set AllowPaging=true but noting happened.
Also I'm using AllowSorting = true and OnSorting="GridView_Sorting". But when I click on the header to sort the the content of that column, it does not enters on my OnSorting="GridView_Sorting" it goes right to the GridView1_RowCommand why ?
Sometimes it just give me this error:
Object reference not set to an instance of an object error
Here's my Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"
CssClass="gridview" OnSorting="GridView_Sorting"
AllowSorting ="True" AllowPaging="True" BackColor="#CCCCCC"
BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
CellPadding="1"
CellSpacing="5"
HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="GridView1_RowDataBound"
ForeColor = "Black" RowStyle-CssClass="gridview"
OnRowCommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<columns>
<asp:BoundField HeaderText="ID" DataField="id" SortExpression="id" />
<asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade" ItemStyle-HorizontalAlign="Center" SortExpression="prioridade" SortExpression="prioridade" />
<asp:BoundField HeaderText="SITUAÇÃO" DataField="situacao" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="65px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" SortExpression="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"ItemStyleHorizontalAlign="Center" >
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PROJETO" DataField="projeto" ItemStyle-HorizontalAlign="Center"></asp:BoundField>
<asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="CLUBE" DataField="clube" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
<ItemTemplate>
<asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial" OnClick="Btn_Visualizar_Click"CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
<ItemTemplate>
<asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
<ItemTemplate>
<asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</columns>
My CodeBehind:
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');
// If the sorting column is the same as the previous one,
// then change the sort order.
if (strSortExpression[0] == e.SortExpression)
{
if (strSortExpression[1] == "ASC")
{
ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
}
// If sorting column is another column,
// then specify the sort order to "Ascending".
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
// Rebind the GridView control to show sorted data.
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
Add SortExpression attribute for each sortable column, informing its DataField.

Categories