Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi again

I scratching my head yet again. Hope you can help.

I have a gridview containing list of equipment. when a person choose a time to book equipment, the system should check the time against the database and toggle the visibility of two controls (checkbox and label). if time clash of overlap is found, then the label should be displayed and checkbox hidden. if not then the other way around is true.

Here is the problem; I have it working as it should, but if time overlap for one equipment is found, then all labels for all equipment is displayed, and checkbox is hidden, if not all checkbox is displayed and label hidden.

I would like to know how I can get it to perform the operation only for rows that have the time overlap or clash, and make other equipment available.

Here is the code behind.

C#
while (reader.Read())
            {
                DataRow dataRow = table.NewRow();

                DateTime startDate = Convert.ToDateTime(reader["StartDate"]);
                DateTime endDate = Convert.ToDateTime(reader["EndDate"]);

                TimeSpan startTime = (TimeSpan)reader["StartTime"];
                TimeSpan endTime = (TimeSpan)reader["EndTime"];
                
                dataRow["SDate"] = startDate;
                dataRow["FDate"] = endDate;
                dataRow["STime"] = startTime;
                dataRow["ETime"] = endTime;
                table.Rows.Add(dataRow);

                
                if (((startDate <= startDateTime && startDateTime <= endDate)
                   || (startDate <= endDateTime && endDateTime <= endDate)
                    || (startDate >= startDateTime && endDateTime >= endDate))
                    && 
                    ((startTime <= starttime && starttime <= endTime)
                || (startTime <= endtime && endtime <= endTime)
                || (startTime >= starttime && endtime >= endTime)))

                {

                            foreach (GridViewRow row in GridView1.Rows)
                            {
               Label LabelUnavailable = (Label)row.FindControl("Label1");
               CheckBox CheckBoxAsset = (CheckBox)row.FindControl("CheckBox1");
                                CheckBoxAsset.Visible = false;
                                LabelUnavailable.Visible = true;
                              }   

                }
                else
                {

                            foreach (GridViewRow row in GridView1.Rows)
                            {
               Label LabelUnavailable = (Label)row.FindControl("Label1");
               CheckBox CheckBoxAsset = (CheckBox)row.FindControl("CheckBox1");
                                CheckBoxAsset.Visible = true;
                                LabelUnavailable.Visible = false;
                            }   
                    
                }

            }


I would really appreciate any suggestion.

Thanks

I changed it as follows, but same result

C#
foreach (GridViewRow gridViewRow in GridView1.Rows)
                {
                    if (((startDate <= startDateTime && startDateTime <= endDate)
                       || (startDate <= endDateTime && endDateTime <= endDate)
                        || (startDate >= startDateTime && endDateTime >= endDate))
                        &&
                        ((startTime <= starttime && starttime <= endTime)
                    || (startTime <= endtime && endtime <= endTime)
                    || (startTime >= starttime && endtime >= endTime)))
                    {



            Label LabelUnavailable = (Label)gridViewRow.FindControl("Label1");
       CheckBox CheckBoxAsset = (CheckBox)gridViewRow.FindControl("CheckBox1");
                        CheckBoxAsset.Visible = false;
                        LabelUnavailable.Visible = true;
                        



                    }

                    else
                    {

                        //foreach (GridViewRow gridViewRow in GridView1.Rows)
                        
             Label LabelUnavailable = (Label)gridViewRow.FindControl("Label1");
       CheckBox CheckBoxAsset = (CheckBox)gridViewRow.FindControl("CheckBox1");
                            CheckBoxAsset.Visible = true;
                            LabelUnavailable.Visible = false;
                        

                    }
                }

            }


Here is GridView and database connection

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" 
                                    Width="700px" BorderColor="#999999" BorderStyle="Solid" BorderWidth="0px" 
                                    CellPadding="16" DataSourceID="SqlDataSource2"  ForeColor ="#333333" GridLines="None"
                                    OnSelectedIndexChanged="GridView1_SelectedIndexChanged" ShowFooter="True" 
                                    OnRowCreated="RowCreated" HorizontalAlign="Center" Visible="False" DataKeyNames="AssetID">
                        <AlternatingRowStyle BackColor="#f1f1f1" />
                        <Columns>
                           <asp:TemplateField>                             
                                
                                <FooterTemplate>
                                    
                                    <asp:Button ID="Confirm" CssClass="buttonConfirm" runat="server" Text="Confirm" Visible="True" />
                                   <asp:Button ID="Cancel" CssClass="buttonCancel" runat="server" Text="Cancel"  Visible="True" OnClick="Cancel_Click" />          
                                    
                        
                                </FooterTemplate>
                                
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server"   />
                                    <asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Unavailable" ></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="Asset" HeaderText="Asset" SortExpression="Asset" />
                            <asp:BoundField DataField="Descriptions" HeaderText="Descriptions" SortExpression="Descriptions" />
                            <asp:BoundField DataField="ObtainMethod" HeaderText="ObtainMethod" SortExpression="ObtainMethod" />
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:Image style="" AlternateText="Image Not Found"  ID ="Image1" Width="60px" runat="server" ImageUrl='<%# Bind("Images") %>' />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>

                        
                        <EmptyDataRowStyle ForeColor="red" HorizontalAlign="Center"/>
                        <FooterStyle BackColor="#ffffff" Width="100%" Height="100%"/> 
                        <HeaderStyle BackColor="white"  ForeColor="White" />
                        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#000099" ForeColor="White" />
                        <SortedAscendingCellStyle BackColor="#F1F1F1" />
                        <SortedAscendingHeaderStyle BackColor="#808080" />
                        <SortedDescendingCellStyle BackColor="#CAC9C9" />
                        <SortedDescendingHeaderStyle BackColor="#383838" />
                    
                        <EmptyDataTemplate>
                            <br>
                            </br>
                            <div style=" background-color:#fffbec; height:20px; width:70%;  border-removed 1px solid red; border-removed 1px solid red;border-radius:8px; padding:2px;">
                                    Please choose your Campus to display available assets


                            </div>
                            <br>
                            </br>
                            <br>
                            </br>
                       </EmptyDataTemplate>
                        
                        
                    </asp:GridView>

                               
                    
                    

                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AssetBookingSystemConnectionString %>" SelectCommand="SELECT * FROM [tblAssets]">
                    </asp:SqlDataSource>


Here is the complete code behind

C#
 protected void CheckAvailability_Click(object sender, EventArgs e)
        {

            DateTime startDateTime = DateTime.ParseExact(StartDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            TimeSpan starttime = TimeSpan.ParseExact(StartTime.SelectedValue, "h\\:mm", CultureInfo.InvariantCulture);


            DateTime endDateTime = DateTime.ParseExact(FinishDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            TimeSpan endtime = TimeSpan.ParseExact(FinishTime.SelectedValue, "h\\:mm", CultureInfo.InvariantCulture);

            //Checking asset is available for booking:


            if ((endDateTime > startDateTime) || (endDateTime == startDateTime))

                GridView1.Visible = true;

            else
                GridView1.Visible = false;

            if ((startDateTime == DateTime.Now.Date) || (endDateTime == DateTime.Now.Date))

                SameDayBooking.Visible = true;
            else
                SameDayBooking.Visible = false;


            if (((FinishTime.SelectedIndex < StartTime.SelectedIndex) || (FinishTime.SelectedIndex == StartTime.SelectedIndex))
                 && ((endDateTime < startDateTime) || (endDateTime == startDateTime)))
            {
                timeError.Visible = true;
                GridView1.Visible = false;


            }
            else
            {
                timeError.Visible = false;
                GridView1.Visible = true;
            }


            
                string cs = System.Configuration.ConfigurationManager.ConnectionStrings["AssetBookingSystemConnectionString"].ConnectionString;



                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand();
                SqlDataReader reader;
                cmd.CommandText = "SELECT StartDate, EndDate, StartTime, EndTime FROM tblBooking";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                con.Open();
                reader = cmd.ExecuteReader();


                DataTable table = new DataTable();
                table.Columns.Add("SDate");
                table.Columns.Add("FDate");
                table.Columns.Add("STime");
                table.Columns.Add("ETime");



                while (reader.Read())
                {
                    DataRow dataRow = table.NewRow();

                    DateTime startDate = Convert.ToDateTime(reader["StartDate"]);
                    DateTime endDate = Convert.ToDateTime(reader["EndDate"]);

                    TimeSpan startTime = (TimeSpan)reader["StartTime"];
                    TimeSpan endTime = (TimeSpan)reader["EndTime"];




                    dataRow["SDate"] = startDate;
                    dataRow["FDate"] = endDate;
                    dataRow["STime"] = startTime;
                    dataRow["ETime"] = endTime;
                    table.Rows.Add(dataRow);

                    foreach (GridViewRow gridViewRow in GridView1.Rows)
                    {
                        if (((startDate <= startDateTime && startDateTime <= endDate)
                           || (startDate <= endDateTime && endDateTime <= endDate)
                            || (startDate >= startDateTime && endDateTime >= endDate))
                            &&
                            ((startTime <= starttime && starttime <= endTime)
                        || (startTime <= endtime && endtime <= endTime)
                        || (startTime >= starttime && endtime >= endTime)))
                        {

                            Label LabelUnavailable = (Label)gridViewRow.FindControl("Label1");
                            CheckBox CheckBoxAsset = (CheckBox)gridViewRow.FindControl("CheckBox1");
                            CheckBoxAsset.Visible = false;
                            LabelUnavailable.Visible = true;


                        }

                        else
                        {



                            Label LabelUnavailable = (Label)gridViewRow.FindControl("Label1");
                            CheckBox CheckBoxAsset = (CheckBox)gridViewRow.FindControl("CheckBox1");
                            CheckBoxAsset.Visible = true;
                            LabelUnavailable.Visible = false;



                        }
                    }

                }
                reader.Close();

                con.Close();


            
        }

    }
}
Posted
Updated 8-Jun-15 9:08am
v4
Comments
[no name] 8-Jun-15 8:30am    
It looks your label and checkbox control visibility is set as per the last record in reader object, as you are iterating through all gridview rows every time you process 1 reader entry. Please correct if wrong.

Have you tried to set this visibility in RowDataBound event for gridview control?
Awoldeselassie 8-Jun-15 8:58am    
Your first sentence is correct. And yes, I have tried. But the RowDataEvent is outside the button event handler, therefore when I refer to the checkbox or label in the IF statement, it keeps saying 'it doesn't exists in this context' that would have been much easier, but I don't know how to reference, for e.g. 'CheckBoxAsset.Visible = false;' and 'LabelUnavailable.Visible = true;' in the IF statement as shown above. Sorry if I sound stupid
[no name] 8-Jun-15 9:04am    
Do you bind this table object as datasource to your gridview control?
Awoldeselassie 8-Jun-15 9:12am    
The datasource for the gridview is a table callen 'tblAssets' as it display the assets.
Datasource for the reader to check if time overlap is occurring, is a table called tblBooking. It looks like its working, but it displays one or the other. If it find time overlap or clash, all assets are unavailable. otherwise all are available.
[no name] 8-Jun-15 9:21am    
Dont you hace any provision to hold this overlap flag value in your datasource which you bind to grid control. If yes then it should work in RowDataBound event to set visibility, otherwise I think you need to maintain this flag somewhere in datasource.

But you need to move that logic to set visibility from your code as above, this will set all rows based on 1 reader entry.

1 solution

You can move code in seperate method to populate data from tblooking.

C#
private DataTable GetBookingDetails(object sender, EventArgs e)
{
 // your code to get from tblBooking here, then
    while (reader.Read())
    {
       //condition to check overlap flag then populate list<bool> which have value for each row for tblBooking now..maintain this on page level e.g. IsOverlapForBooking
    }
}</bool>



C#
protected void CheckAvailability_Click(object sender, EventArgs e)
{
    // comment your code to read tblBooking and reader implementation here
    GridView1.DataSourceID = null; // because we want to bind here on click event, this will error our as you have SqlDataSource attached to grid control.
    GridView1.DataSource = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    GridView1.DataBind();
}



So here now you have DataSource availale to bind with GridControl with SqlDataSource, then List<bool> overlap flag for each booking you have in tblBooking table which you build in GetBookingDetails and page level variable, so when you click CheckAvailability button now use RowDataBound to iterate through overlap flag list and then based on value you can set visibility of lable and checkbox control..

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label label = e.Row.FindControl("label") as Label;
        CheckBox checkBox = e.Row.FindControl("checkBox") as CheckBox;
         
        //this you populated on GetBookingDetails for each row
        if(IsOverlapForBooking[e.Row.RowIndex])
        {
           // overlap = true then do something
        }
        else
        {
           // overlap = false then do something
        }
    }
}


this may not be a perfect solution but you asked for suggestion and i tried. Hope you can find some better solution than this... lol :)
 
Share this answer
 
Comments
Awoldeselassie 12-Jun-15 10:10am    
Your suggestion is perfect, I will go through my code and change it. thanks for the help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900