Hide Gridview column when null - asp.net

I have a gridview in the front end showing 4-5 columns. Need to hide one of the column when the values are NULL.
<asp:GridView ID="gvProducts" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" AutoGenerateColumns="False" AllowPaging="True" PageSize="100" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="CategoryId" SortExpression="CategoryId" HeaderText="CategoryId" Visible="false" />
<asp:BoundField DataField="MerchantName" HeaderText="MerchantName" SortExpression="MerchantName" />
<asp:BoundField DataField="StoreName" HeaderText="StoreName" SortExpression="StoreName" />
<asp:BoundField DataField="StoreAddress" HeaderText="StoreAddress" SortExpression="StoreAddress" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
If I want to hide StoreName column from code-behind. How to achieve that ?

You can Use RowDataBound Event of GridView
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string val = e.Row.Cells[0].ToString(); //check first cell value
if(string.IsNullorEmpty(val) )
{
gvSearchEngine.Columns[0].Visible = false; //Hides First Column
}
}
}

Yes, you can dynamically create the boundfield values
from code behind based on your requirment
follow this link
add boundField to gridview in codebehind file C#

try e.Row.Cells[0].Controls[0].Visible = false;

Related

Delete Link Button not working in GridView using ASP

So there's not much to explain, I have a GridView and I put a Delete button which asks if you're sure you want to delete when you click it. I'm using VisualStudio2012 and I've done this in many other pages but I've never gotten this problem.
GridView:
<asp:GridView ID="MaintenanceTable" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Maintenance_ID" DataSourceID="MaintDataSource" EmptyDataText="There are no data records to display." BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" Width="1000px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="DeleteButton" Text="Delete"
CommandName="delete"
OnClientClick="if (!window.confirm('Are you sure you want to delete this item?')) return false;" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="Maintenance_ID" HeaderText="Maintenance_ID" InsertVisible="False" ReadOnly="True" SortExpression="Maintenance_ID" />
<asp:CheckBoxField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#34397D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
This really is the only code I've added in terms of deleting in my GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="DeleteButton" Text="Delete"
CommandName="delete"
OnClientClick="if (!window.confirm('Are you sure you want to delete this item?')) return false;" />
</ItemTemplate>
</asp:TemplateField>
You need to add the following code:
protected void MaintenanceTable_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
// get the maintenanceId of the clicked row
int maintenanceId = Convert.ToInt32(e.CommandArgument);
// Delete the record
DeleteRecordByID(maintenanceId);
// Implement
}
}
Just incase, make sure you use "Delete" not "delete".
Check this resource GridView Delete, with Confirmation

Remove Empty row in gridview which is added automatically at the bottom of gridview

I am using grid view to show records from database. Gridview has pagination and pagesize is set as 15. And one column has link field when user click this link it proceed some functionality. Now what is my problem is
1) when number of records less than page size the last page is
shrunk. it's k for me. but on clicking view link in grid view the
empty row added automatically. how do i remove these empty row?
2) on clicking view link the page index changed to 1. example i am in
3 page of grid view and clicking view link in 3rd page the page index
number changed to 1 but the page shows 3rd row record. how do i fix
this..?
please any can help me.. thanks in advance
grid view code:-
<asp:GridView ID="gvGRNListAll" runat="server" AutoGenerateColumns="False" Style="width: 100%;"
AllowPaging="True" PageSize="15" OnPageIndexChanging="gvGRNListAll_PageIndexChanging"
CellPadding="4" ForeColor="#333333" BorderColor="#CCCCCC" ShowHeaderWhenEmpty="True"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<PagerStyle CssClass="pager" />
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="10%" />
</asp:TemplateField>
<asp:BoundField DataField="LocationName" HeaderText="Location" />
<asp:BoundField DataField="SupplierName" HeaderText="Supplier Name" />
<asp:BoundField DataField="GRNNo" HeaderText="GRN No" />
<asp:BoundField DataField="InvoiceNo" HeaderText="In.No">
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="GRNDate" HeaderText="GRNDate" />
<asp:TemplateField HeaderText="Action" SortExpression="ExId" ControlStyle-ForeColor="Blue">
<ItemTemplate>
<asp:HiddenField ID="hdnStoreCode" runat="server" Value='<%# Eval("StoreCode") %>' />
<asp:HiddenField ID="hdnGRNNo" runat="server" Value='<%# Eval("GRNNo") %>' />
<asp:LinkButton ID="lbView" OnClick="lbView_Click" runat="server" Text="View"></asp:LinkButton>
</ItemTemplate>
<ControlStyle ForeColor="#FF3300" />
<HeaderStyle CssClass="GridHeaderROW" Width="10%" />
<ItemStyle CssClass="GridItemROW" Width="10%" />
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Bottom" ForeColor="#FF3300" />
<EmptyDataTemplate>
No Records Found.
</EmptyDataTemplate>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<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>
On PageIndexChanged
protected void gvGRNListAll_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvGRNListAll.PageIndex = e.NewPageIndex;
SearchData();
gvGRNListAll.PageIndex = 0;
}
Searchdata Code :
public void SearchData()
{
DataTable dtGRN = objBAL.FilterGRNScannedList("filterGRNScannedList", suppliercode, grnno, locationcode, Fromdate, Todate, "");
gvGRNListAll.DataSource = dtGRN;
gvGRNListAll.DataBind();
}
Onclick event Code :
if (sender is LinkButton)
{
GridViewRow gvrCurrent = ((LinkButton)sender).NamingContainer as GridViewRow;
hdnGRNNo = (HiddenField)gvrCurrent.FindControl("hdnGRNNo");
hdnStore = (HiddenField)gvrCurrent.FindControl("hdnStoreCode");
gvGRNListAll.Rows[gvrCurrent.RowIndex].BackColor = System.Drawing.Color.Empty;
gvGRNListAll.Rows[gvrCurrent.RowIndex].BackColor = System.Drawing.ColorTranslator.FromHtml("#D8D8D8");
if (hdnGRNNo != null && hdnStore != null)
{
GetGRNListForNo(hdnGRNNo.Value, Convert.ToInt32(hdnStore.Value));
}
}
on RowDataBound do something like below
private void gvGRNListAll_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[6].Text == "") // here add the cell no at which the row is coming blank.
e.Row.Visible = false;
}
Hope it helps

Incorrect syntax near 'int' when using updatecommand on a gridview

I have a problem that when ever I try to update a record in the database using gridview update event handler and an updatecommand in sqldatascource
I get the following exception
Incorrect syntax near 'int'.
the weird thing is when I reload the page I find that the record was updated successfully but yet I need this exception message not to appear what should I do
update event handler
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BusId = Convert.ToInt32(((DataKey)GridView1.DataKeys[e.RowIndex]).Value);
TextBox Capacity =(TextBox) row.Cells[1].Controls[0];
TextBox DriverName =(TextBox) row.Cells[3].Controls[0];
TextBox Phone =(TextBox) row.Cells[4].Controls[0];
SqlDataSource1.UpdateParameters.Add("capaity", Capacity.Text);
SqlDataSource1.UpdateParameters.Add("id", BusId.ToString());
SqlDataSource1.UpdateParameters.Add("driver", DriverName.Text);
SqlDataSource1.UpdateParameters.Add("phone", Phone.Text);
SqlDataSource1.Update();
}
gridview asp.net code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Bus Number" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="326px" Width="1017px" OnRowUpdating="GridView1_RowUpdating">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Bus Number" HeaderText="Bus Number" ReadOnly="True" SortExpression="Bus Number" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" SortExpression="Capacity" />
<asp:BoundField DataField="NumberOfBooking" HeaderText="NumberOfBooking" SortExpression="NumberOfBooking" ReadOnly="True" />
<asp:BoundField DataField="Driver" HeaderText="Driver" SortExpression="Driver" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" ShowHeader="False" />
<asp:BoundField DataField="Date Added" HeaderText="Date Added" SortExpression="Date Added" DataFormatString="{0:MM/dd/yyyy}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
the updatecommand
UpdateCommand="UPDATE Buses SET Capacity = #capaity WHERE VechileId = #id ;UPDATE Vechile SET Driver = #driver, Phone = #phone
WHERE VechileId = #id">

How to Display the search Data in GridView ?

My GridViews which are connected to their respective LinqDataSource(LinqDataSourceMale & LinqDataSourceFemale) are
<asp:GridView ID="GridViewMale" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" ForeColor="Black" GridLines="Horizontal" PageSize="5" Width="692px" DataSourceID="LinqDataSourceMale">
<Columns>
<asp:ImageField DataImageUrlField="Image" NullImageUrl="images/bullet.png" ReadOnly="True">
</asp:ImageField>
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Education" HeaderText="Education" SortExpression="Education" />
<asp:BoundField DataField="CurrentStatus" HeaderText="CurrentStatus" SortExpression="CurrentStatus" />
<asp:BoundField DataField="Height" HeaderText="Height" SortExpression="Height" />
<asp:BoundField DataField="Complexion" HeaderText="Complexion" SortExpression="Complexion" />
<asp:BoundField DataField="Caste" HeaderText="Caste" SortExpression="Caste" />
<asp:BoundField DataField="Group" HeaderText="Group" SortExpression="Group" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSourceMale" runat="server" ContextTypeName="MB.BerouDataContext" EntityTypeName="" TableName="Males">
</asp:LinqDataSource>
<asp:GridView ID="GridViewFemale" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" ForeColor="Black" GridLines="Horizontal" PageSize="5" Width="693px" DataSourceID="LinqDataSourceFemale">
<Columns>
<asp:ImageField DataImageUrlField="Image" >
</asp:ImageField>
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Education" HeaderText="Education" SortExpression="Education" />
<asp:BoundField DataField="CurrentStatus" HeaderText="CurrentStatus" SortExpression="CurrentStatus" />
<asp:BoundField DataField="Height" HeaderText="Height" SortExpression="Height" />
<asp:BoundField DataField="Complexion" HeaderText="Complexion" SortExpression="Complexion" />
<asp:BoundField DataField="Caste" HeaderText="Caste" SortExpression="Caste" />
<asp:BoundField DataField="Group" HeaderText="Group" SortExpression="Group" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" Wrap="True" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSourceFemale" runat="server" ContextTypeName="MB.BerouDataContext" EntityTypeName="" TableName="Females">
</asp:LinqDataSource>
My SearchClick event code is:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
using(BerouDataContext Data = new BerouDataContext())
{
if (DropDownListGender.SelectedItem.Text == "Male")
{
int age = Convert.ToInt32(DropDownListAge.Text);
string education = DropDownListEducation.Text.ToString();
string maritalstatus = DropDownListMaritalStatus.Text.ToString();
string caste = DropDownListCaste.Text.ToString();
string city = DropDownListCity.ToString();
var SearchResultBoys = Data.Males.Where(tan =>
(tan.Age == age)
&& (tan.Education.Contains(education))
&& (tan.Group.Contains(maritalstatus))
&& (tan.Caste.Contains(caste)));
GridViewMale.DataSourceID = "";
GridViewMale.DataSource = SearchResultBoys;
GridViewMale.DataBind();
}
else if (DropDownListGender.SelectedItem.Text == "Female")
{
int age = Convert.ToInt32(DropDownListAge.Text);
string education = DropDownListEducation.Text.ToString();
string maritalstatus = DropDownListMaritalStatus.Text.ToString();
//var religion = DropDownListReligion.Text.ToString();
string caste = DropDownListCaste.Text.ToString();
string city = DropDownListCity.ToString();
var SearchResultGirls = Data.Females.Where(tan =>
(tan.Age == age)
&& (tan.Education.Contains(education))
&& (tan.Group.Contains(maritalstatus))
&& (tan.Caste.Contains(caste)));
GridViewFemale.DataSourceID = "";
GridViewFemale.DataSource = SearchResultGirls;
GridViewFemale.DataBind();
}
}
}
Iam unable to display the data in gridview, gridview doesnt apper after searchClickEvent, please Help.
I think you might need to re-initlize your LinqDataSource data source instead of gridview
Take a look at this tutorial and this thread

How to make a Gridview template field select the row of data?

I have a command field in a gridview, that as it is, works as it should. When i select it, the row is hilighted. However, i needed to convert this field into a template, so i could give it a ID that i could reference when using a AJAX Mobal control. I did this, and i am able to reference it with my Ajax control just fine, but, now this field does not select the row in the Gridview? The Select value is needed for the Ajax control to pull the data thru. So i think my issue is, How do i use this command field as a template, AND have it select the row? I hope i am explaining my issue correctly.
Here is the snippet of code when i convert it into a template.
Thank you!
<asp:GridView ID="GridView3" runat="server" AllowPaging="True" AutoGenerateColumns="False" CellPadding="3" DataKeyNames="Contact_ID" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="None" PageSize="6">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select" Text="Edit"></asp:LinkButton>
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="LinkButton1" PopupControlID="DetailsView1" BackgroundCssClass="modalBackground"></asp:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Contact_ID" HeaderText="Contact_ID" InsertVisible="False" ReadOnly="True" SortExpression="Contact_ID" Visible="False" />
<asp:BoundField DataField="Contact_Assigned_Username" HeaderText="Username" SortExpression="Contact_Assigned_Username" />
<asp:BoundField DataField="Contact_First_Name" HeaderText="First Name" SortExpression="Contact_First_Name" />
<asp:BoundField DataField="Contact_Last_Name" HeaderText="Last Name" SortExpression="Contact_Last_Name" />
<asp:BoundField DataField="Contact_Email_Address" HeaderText="Email Address" SortExpression="Contact_Email_Address" />
<asp:BoundField DataField="Contact_Cell_Phone" HeaderText="Cell Phone" SortExpression="Contact_Cell_Phone" />
<asp:CheckBoxField DataField="Contact_Administrator" HeaderText="Admin" SortExpression="Contact_Administrator" />
<asp:CheckBoxField DataField="Contact_LineStat_Triggers_Email" HeaderText="Email Triggers" SortExpression="Contact_LineStat_Triggers_Email" />
<asp:CheckBoxField DataField="Contact_LineStat_Triggers_Text" HeaderText="Text Triggers" SortExpression="Contact_LineStat_Triggers_Text" />
<asp:CheckBoxField DataField="Contact_Web_Portal" HeaderText="Web Access" SortExpression="Contact_Web_Portal" />
<asp:BoundField DataField="Contact_Customer_ID" HeaderText="Contact_Customer_ID" SortExpression="Contact_Customer_ID" Visible="False" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
In the RowDataBound event, try something like this:
protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton btn = (LinkButton)e.Row.FindControl("LinkButton1");
btn.OnClientClick = Page.ClientScript.GetPostBackEventReference(GridView3, "Select$" + e.Row.RowIndex.ToString()));
}

Resources