How to insert multiple check checked/unchecked boxes value into database from aspxgridview checkbox dataitemtemplate? - asp.net

I'm trying to insert multiple checked/unchecked box value into database via submit button. after the submit button is clicked, the one or multiple checked check box value will be inserted into database first and followed by checked/unchecked images will appear on the clicked check boxes (which checked image represents value 1 and unchecked image represents value 0. )
Problem :
I have tried the method below but only able to insert one check box value into database, for the outcome the check box appeared as number instead of checked/unchecked image and required to refresh the page for the checked/unchecked images to appear.
Aspx
<dx:ASPxComboBox ID="year" runat="server" AutoPostBack="true" ClientInstanceName="year" ValueType="System.Int32" Width="100px" CssClass="ddstyle mr10px" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
<dx:ASPxComboBox ID="month" runat="server" AutoPostBack="true" ClientInstanceName="month" ValueType="System.Int32" Width="100px" CssClass="ddstyle mr10px" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
<dx:ASPxComboBox ID="section" runat="server" AutoPostBack="true" ValueType="System.String" Width="100px" CssClass="ddstyle" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
</div>
</div>
<dx:ASPxGridView ID="LeaveSystem" runat="server" AutoGenerateColumns="false" KeyFieldName="EMP_NO;Year;Month" Width="100%">
<SettingsBehavior AllowDragDrop="false" AllowSort="false" />
<SettingsPager Mode="ShowAllRecords" />
</dx:ASPxGridView>
<asp:UpdateProgress ID="GeneralUpdateProgress" ClientIDMode="Static" runat="server">
<ProgressTemplate>
<img id="gupLoading" src="../images/loadingscreen.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<dx:ASPxCallback ID="cb" ClientInstanceName="cb" runat="server" OnCallback="cb_Callback" ></dx:ASPxCallback>
<dx:ASPxLabel ID="HiddenEmpID" runat="server" ClientInstanceName="HiddenEmpID" ClientVisible="false"></dx:ASPxLabel>
<dx:ASPxButton ID="submitbtn" runat="server" Text="Submit" Visible="true" OnClick="submitbtn_Click" AutoPostBack="false"></dx:ASPxButton>
VB.net
Sub CustomCheckBoxColumn(ByVal fieldName As String)
Dim c As New GridViewDataColumn
c.DataItemTemplate = New CheckBoxTemplate
c.FieldName = fieldName
Dim dayOfDate As New DateTime
dayOfDate = getDate(fieldName)
c.Caption = c.FieldName + vbNewLine + Replace(dayOfDate.ToString("dddd"), "??", "")
c.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
c.CellStyle.HorizontalAlign = HorizontalAlign.Center
LeaveSystem.Columns.Add(c)
End Sub
Function getDate(ByVal fieldName As String) As DateTime
Dim chosenDate As New DateTime
chosenDate = Convert.ToDateTime(year.Value.ToString() + "-" + month.Value.ToString() + "-" + fieldName)
Return chosenDate
End Function
Protected Sub SelectedIndexChanged(sender As Object, e As EventArgs)
LeaveSystem.DataBind()
End Sub
Private Sub LeaveSystem_DataBinding(sender As Object, e As EventArgs) Handles LeaveSystem.DataBinding
LeaveSystem.Columns.Clear()
Dim sql As String = ""
If section.Value.ToString() = "PT" Then
sql = "select * from tb1"
Else
sql = "select * from tb2"
End If
Dim dt As New DataTable
dt = GetMssql(sql)
LeaveSystem.DataSource = dt
Dim a As New GridViewDataColumn
a.FieldName = "EMP_NO"
a.Caption = "EMPID"
LeaveSystem.Columns.Add(a)
Dim b As New GridViewDataColumn
b.FieldName = "CHI_NAME"
b.Caption = "CNAME"
LeaveSystem.Columns.Add(b)
Dim fieldName As String = ""
Dim lastDay As New Integer
lastDay = DateTime.DaysInMonth(DirectCast(year.Value, Integer), DirectCast(month.Value, Integer))
For i = 1 To lastDay
If i.ToString().Length = 1 Then
fieldName = "0" + i.ToString()
Else
fieldName = i.ToString
End If
CustomCheckBoxColumn(fieldName)
Next
End Sub
Friend Class CheckBoxTemplate
Implements ITemplate
Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
Dim checkbox As New ASPxCheckBox
Dim gridContainer As GridViewDataItemTemplateContainer = CType(container, GridViewDataItemTemplateContainer)
'Dim empid As String = gridContainer.Grid.GetRowValues(gridContainer.VisibleIndex, "EmpID").ToString()
checkbox.AllowGrayed = False
checkbox.CheckedImage.Url = "images/checked_image.png"
checkbox.UncheckedImage.Url = "images/unchecked_image.png"
checkbox.CssClass += "customcheckbox"
checkbox.ID = "DateCheckBox"
Dim list As New ArrayList
list.Add(checkbox.Checked)
Dim x As String
For Each x In list
checkbox.ClientSideEvents.CheckedChanged = String.Format("function (s, e) {{ cb.PerformCallback(HiddenEmpID.GetValue() + '|' + year.GetValue() + '|' + month.GetValue() + '|' + '{0}|' + s.GetChecked(""" & x & """)); }}", gridContainer.Column.FieldName)
checkbox.Value = DataBinder.Eval(gridContainer.DataItem, gridContainer.Column.FieldName)
If checkbox.Value = 1 Then
checkbox.Checked = True
Else
checkbox.Checked = False
End If
checkbox.ValueType = GetType(Int32)
checkbox.ValueUnchecked = 0
checkbox.ValueChecked = 1
Next
container.Controls.Add(checkbox)
End Sub
End Class
Protected Sub cb_Callback(source As Object, e As CallbackEventArgs)
Session("par") = e.Parameter.Split("|"c)
End Sub
Protected Sub submitbtn_Click(sender As Object, e As EventArgs)
If IsPostBack Then
Dim p() As String = Session("par")
p(1) = Session("year")
p(2) = Session("month")
'Dim p() As String = e.Parameter.Split("|"c)
'p(0) = empid, p(1) = year, p(2) = month, p(3) = Date, p(4) = Boolean
Dim list As New ArrayList
list.Add(p(3))
If p(4) = True Then
p(4) = "1"
Else
p(4) = "0"
End If
Dim x As String
For Each x In list
Dim query As String = String.Format("UPDATE LeaveSystem SET [{3}] = '{4}', UpdateTime = GETDATE() WHERE EmpID = '{0}' and Year = '{1}' and Month = '{2}' IF ##ROWCOUNT=0 INSERT INTO LeaveSystem (EmpID, Year, Month, [{3}], UpdateTime) values ('{0}', '{1}', '{2}', '{4}', GETDATE())", p(0), p(1), p(2), x, p(4))
SetMssql(query)
Next
End If
End Sub
Expected Result
YEAR : 2019 MONTH: 4
------------------------------------------------------------------
|EMP NO| 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|.....|
------------------------------------------------------------------
| 234 |v | | | | | | | | | | | | | |v | | | | | |.....|
-------------------------------------------------------------------
-->| 456 | v| | | | | | | | | | |v | v| v| | v| | | | |.....|
------------------------------------------------------------------
(Submit) (cancel)
Actual Result
YEAR : 2019 MONTH: 4
------------------------------------------------------------------
|EMP NO| 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|.....|
------------------------------------------------------------------
| 234 | 1| | | | | | | | | | | | | | 1| | | | | |.....|
-------------------------------------------------------------------
-->| 456 | 1| | | | | | | | | | |1 | | 1| 0| 1| | | | |.....|
------------------------------------------------------------------
(Submit) (cancel)

I don't know about VB.net. I am a PHP Developer.
but in this multiple radio check buttons value.
<form method="POST" action="submit.php" >
<input type="checkbox" name="gender" value="male" />
<input type="checkbox" name="gender" value="female" />
<input type="submit" name="submit" value="submit">
</form>
$_POST['gender']={male,female};
`````````````````````
after submitting the form you will get an array of this multiple radio check value.
that's it.

Related

How to check the number of count for aspxgridview checkbox in DataItemTemplate for specific row?

Scenario :
I have a ASPxGridview on client side and used checkbox control on server side. I have declared a aspxbutton(submit) to insert the checked checkbox value (v=1, empty=0) into database and at the same time count the number of checked checkbox for each row. In the checkboxtemplate, v indicates checked and empty indicates unchecked, and the number in the column indicates day based on the month. I want to count the number of checked checkbox for the emp no :234.
YEAR : 2019 MONTH: 3
------------------------------------------------------------------
|EMP NO| 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|.....|
------------------------------------------------------------------
| 123 | v| | | | | | | | | | | | | | v| | | | | |.....|
-------------------------------------------------------------------
-->| 234 | v| | | | | | | | | | |v | v| v| | v| | | | |.....|
------------------------------------------------------------------
(Submit) (cancel)
Code for aspxgridview (aspx)
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="flexs">
<dx:ASPxComboBox ID="year" runat="server" AutoPostBack="true" ClientInstanceName="year" ValueType="System.Int32" Width="100px" CssClass="ddstyle mr10px" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
<dx:ASPxComboBox ID="month" runat="server" AutoPostBack="true" ClientInstanceName="month" ValueType="System.Int32" Width="100px" CssClass="ddstyle mr10px" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
<dx:ASPxComboBox ID="section" runat="server" AutoPostBack="true" ValueType="System.String" Width="100px" CssClass="ddstyle" OnSelectedIndexChanged="SelectedIndexChanged"></dx:ASPxComboBox>
</div>
</div>
<dx:ASPxGridView ID="LeaveSystem" runat="server" AutoGenerateColumns="false" KeyFieldName="EMP_NO;Year;Month" Width="100%">
<SettingsBehavior AllowDragDrop="false" AllowSort="false" />
<SettingsPager Mode="ShowAllRecords" />
</dx:ASPxGridView>
</ContentTemplate>
</asp:UpdatePanel>
<dx:ASPxCallback ID="cb" ClientInstanceName="cb" runat="server" OnCallback="cb_Callback" ></dx:ASPxCallback>
<dx:ASPxLabel ID="HiddenEmpID" runat="server" ClientInstanceName="HiddenEmpID" ClientVisible="false"></dx:ASPxLabel>
<div class="flexs5 mt10px text-center">
<dx:ASPxButton ID="submitbtn" runat="server" Text="Submit" OnClick="submitbtn_Click" AutoPostBack="false" CssClass="mr10px"></dx:ASPxButton>
</div>
Code vb.net
Friend Class CheckBoxTemplate
Implements ITemplate
Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
Dim checkbox As New ASPxCheckBox
Dim gridContainer As GridViewDataItemTemplateContainer = CType(container, GridViewDataItemTemplateContainer)
'Dim empid As String = gridContainer.Grid.GetRowValues(gridContainer.VisibleIndex, "EmpID").ToString()
checkbox.AllowGrayed = False
checkbox.CheckedImage.Url = "images/checked_image.png"
checkbox.UncheckedImage.Url = "images/unchecked_image.png"
checkbox.CssClass += "customcheckbox"
checkbox.ID = "DateCheckBox"
checkbox.ClientSideEvents.CheckedChanged = String.Format("function (s, e) {{ cb.PerformCallback(HiddenEmpID.GetValue() + '|' + year.GetValue() + '|' + month.GetValue() + '|' + '{0}|' + s.GetChecked()); }}", gridContainer.Column.FieldName)
checkbox.Value = DataBinder.Eval(gridContainer.DataItem, gridContainer.Column.FieldName)
If checkbox.Value = 1 Then
checkbox.Checked = True
Else
checkbox.Checked = False
End If
checkbox.ValueType = GetType(Int32)
checkbox.ValueUnchecked = 0
checkbox.ValueChecked = 1
container.Controls.Add(checkbox)
End Sub
End Class
Protected Sub cb_Callback(source As Object, e As CallbackEventArgs)
Session("par") = e.Parameter.Split("|"c)
End Sub
Problem :
I have searched online and tried method below , But it doesn't seem to work.
Protected Sub submitbtn_Click(sender As Object, e As EventArgs)
' Dim fieldname1 As String = ""
If IsPostBack Then
Dim p() As String = Session("par")
'Dim p() As String = e.Parameter.Split("|"c)
'p(0) = empid, p(1) = year, p(2) = month, p(3) = Date, p(4) = Boolean
If p(4) = True Then
p(4) = "1"
Else
p(4) = "0"
End If
Dim query As String = String.Format("UPDATE LeaveSystem SET [{3}] = '{4}', UpdateTime = GETDATE() WHERE EmpID = '{0}' and Year = '{1}' and Month = '{2}' IF ##ROWCOUNT=0 INSERT INTO LeaveSystem (EmpID, Year, Month, [{3}], UpdateTime) values ('{0}', '{1}', '{2}', '{4}', GETDATE())", p(0), p(1), p(2), p(3), p(4))
SetMssql(query)
End If
'' Check exceed 13 days
Dim count1 As Integer = 0
For I As Integer = 0 To LeaveSystem.VisibleRowCount - 1
Dim chkRow As ASPxCheckBox = TryCast(LeaveSystem.FindRowCellTemplateControl(I, Nothing, "cb"), ASPxCheckBox)
For k As Integer = 2 To LeaveSystem.Columns.Count - 1
Dim aheaderCb = TryCast(LeaveSystem.FindHeaderTemplateControl(LeaveSystem.Columns(k), "cb1"), ASPxCheckBox)
If chkRow.IsVisible = True Then
If aheaderCb.Checked = True Then
count1 = count1 + 1
End If
End If
Next k
Next I
End Sub
When executing the submit button, the Object reference not set to an instance of an object error appear on line : If chkRow.IsVisible = True Then. I have attempted for many times but the same outcome appeared. Please guide me on this.
Try That
protected void btnGetRecord_Click(object sender, EventArgs e)
{
var checkedRows = (from GridViewRow row in myGrid.Rows
let checkbox = (CheckBox)row.FindControl("chkSelect")
where checkbox != null && checkbox.Checked == true
select row).ToList();
}
You can convert the code into VB.NET.

Need to query two tables in ASP.NET to fill ajax AutoCompleteExtender

Okay, I am trying to fill my ajax auto complete with values from 2 tables. The two tables don't have any matches. I just need to query both.
This is what i have working for one table [JD]. Just need to add the table [IH] with the same column OEMSubNumber
<System.Web.Script.Services.ScriptMethod(), _
System.Web.Services.WebMethod()> _
Public Shared Function SearchNumbers(ByVal prefixText As String, ByVal count As Integer) As List(Of String)
'Declaring Connection String
Dim sqlConnectionString As String
sqlConnectionString = ConfigurationManager.ConnectionStrings("baminterchangerConnectionString").ConnectionString
Dim sqlConnection As New SqlConnection(sqlConnectionString)
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = "select OEMSubNumber from JD where" & _
" OEMSubNumber like #SearchText + '%'"
cmd.Parameters.AddWithValue("#SearchText", prefixText)
cmd.Connection = sqlConnection
sqlConnection.Open()
Dim customers As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
customers.Add(sdr("OEMSubNumber").ToString)
End While
sqlConnection.Close()
Return customers
End Function
I read the posted link below and tried out the UNION and select * but still not getting this.
Here's and example
JD: IH:
+--------------+----------+ +--------------+----------+
| OEMSubNumber | Desc | | OEMSubNumber | Desc |
+--------------+----------+ +--------------+----------+
| R1245 | Sprocket | | 1354C1 | Gasket |
| L6125 | Flange | | 1542A2 | Pulley |
+--------------+----------+ +--------------+----------+
I need the query to join the tables like so
+--------------+
| OEMSubNumber |
+--------------+
| R1245 |
| L6125 |
| 1354C1 |
| 1542A2 |
+--------------+
This way i can use my #SearchText to find matches for my auto complete.
Don't do a select * since you only need one field. But do use union. Modify your command as
cmd.CommandText = "select OEMSubNumber from JD where OEMSubNumber like #SearchText + '%'"
cmd.CommandText &= " union "
cmd.CommandText &= "select OEMSubNumber from IH where OEMSubNumber like #SearchText + '%'"

Show items in dropdownlist that is not equal to the selected item in other dropdownlist

Example I have 5 DropDownList with values
red, orange, yellow, green, blue
if DropDownList1 select red
The choices for DropDownList2-5 will be
orange, yellow, green, blue
if DropDownList2 select yellow
The choices for DropDownList3-5 will be
orange, green, blue
Here is the code I found in the internet, this is only for 3 DropDownList but what I need is for 5 DropDownList. I can't expand the code for 5 DropDownList
VB
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Private bFlag As Boolean = True
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
FillddlLocations()
End If
End Sub
'Properties to store selected value in ViewState
Protected Property MemberID1Selection() As String
Get
If ViewState("MemberID1Selection") IsNot Nothing Then
Return ViewState("MemberID1Selection").ToString()
End If
Return ""
End Get
Set(value As String)
ViewState("MemberID1Selection") = value
End Set
End Property
Protected Property MemberID2Selection() As String
Get
If ViewState("MemberID2Selection") IsNot Nothing Then
Return ViewState("MemberID2Selection").ToString()
End If
Return ""
End Get
Set(value As String)
ViewState("MemberID2Selection") = value
End Set
End Property
Protected Property MemberID3Selection() As String
Get
If ViewState("MemberID3Selection") IsNot Nothing Then
Return ViewState("MemberID3Selection").ToString()
End If
Return ""
End Get
Set(value As String)
ViewState("MemberID3Selection") = value
End Set
End Property
Protected Sub FillddlLocations()
FillDropdown(companyID1)
FillDropdown(companyID2)
FillDropdown(companyID3)
companyID1.Visible = True
companyID2.Visible = True
companyID3.Visible = True
End Sub
Protected Sub FillDropdown(ddl As DropDownList)
Using connAdd = New SqlConnection("Data Source = MENDOZAABBY-PC\SQLEXPRESS; Initial Catalog = ThesisDatabase; Integrated Security= True")
connAdd.Open()
Dim sql = "SELECT CompanyName FROM Company Where College = 'CCS'"
Using cmdAdd = New SqlDataAdapter(sql, connAdd)
Dim ds2 As New DataSet()
cmdAdd.Fill(ds2)
ddl.Items.Clear()
ddl.DataSource = ds2
ddl.DataTextField = "CompanyName"
ddl.DataValueField = "CompanyName"
ddl.DataBind()
ddl.Items.Insert(0, New ListItem("Please select a Company", ""))
ddl.SelectedIndex = 0
End Using
End Using
End Sub
Protected Sub IndexChanged(ddlChanged As DropDownList, ddlToFilter1 As DropDownList, ddlToFilter2 As DropDownList)
Dim removeValue1 As String = If(ddlChanged Is companyID1, MemberID1Selection, (If(ddlChanged Is companyID2, MemberID2Selection, MemberID3Selection)))
Dim selValue2 As String = If(ddlChanged Is companyID1, MemberID2Selection, (If(ddlChanged Is companyID2, MemberID1Selection, MemberID1Selection)))
Dim selValue3 As String = If(ddlChanged Is companyID1, MemberID3Selection, (If(ddlChanged Is companyID2, MemberID3Selection, MemberID2Selection)))
bFlag = False
'Prevent fireing the code again while changing the index
If removeValue1 <> "" Then
Dim item1 As ListItem = ddlToFilter1.Items.FindByValue(removeValue1)
ddlToFilter1.Items.Remove(item1)
Dim item2 As ListItem = ddlToFilter2.Items.FindByValue(removeValue1)
ddlToFilter2.Items.Remove(item2)
End If
If selValue3 <> "" Then
Dim item3 As ListItem = ddlToFilter1.Items.FindByValue(selValue3)
ddlToFilter1.Items.Remove(item3)
End If
If selValue2 <> "" Then
Dim item4 As ListItem = ddlToFilter2.Items.FindByValue(selValue2)
ddlToFilter2.Items.Remove(item4)
End If
bFlag = False
ddlToFilter1.SelectedIndex = ddlToFilter1.Items.IndexOf(ddlToFilter1.Items.FindByValue(selValue2))
ddlToFilter2.SelectedIndex = ddlToFilter2.Items.IndexOf(ddlToFilter2.Items.FindByValue(selValue3))
End Sub
Protected Sub ddlpid1_SelectedIndexChanged(sender As Object, e As EventArgs)
MemberID1Selection = companyID1.SelectedValue
If bFlag Then
FillDropdown(companyID2)
FillDropdown(companyID3)
IndexChanged(companyID1, companyID2, companyID3)
End If
End Sub
Protected Sub ddlpid2_SelectedIndexChanged(sender As Object, e As EventArgs)
MemberID2Selection = companyID2.SelectedValue
If bFlag Then
FillDropdown(companyID1)
FillDropdown(companyID3)
IndexChanged(companyID2, companyID1, companyID3)
End If
End Sub
Protected Sub ddlpid3_SelectedIndexChanged(sender As Object, e As EventArgs)
MemberID3Selection = companyID3.SelectedValue
If bFlag Then
FillDropdown(companyID1)
FillDropdown(companyID2)
IndexChanged(companyID3, companyID1, companyID2)
End If
End Sub
End Class
ASPX
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="companyID1" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="companyID2" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="companyID3" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
</div>
</form>
</body>
</html>
Let Me give you an idea, which will work. Create a matrix object. It could be an array.
Items -> | red | orange | yellow | green |
Controls | | | | |
| | | | | |
V | | | | |
_________|______|________|________|_______|
combo1 |true | false | true |true |
_________|______|________|________|_______|
combo2 |true | false | true |true |
_________|______|________|________|_______|
combo3 |true | false | true |true |
_________|______|________|________|_______|
combo4 |true | true | true |true |
_________|______|________|________|_______|
Update:
According to this matrix your interface will have combo4 items - All, other combos will only have red, yellow and green.
when combo3 is clicked next and, for example, yellow selected you will fill the cell "combo3/yellow" with "true" and other remaining cells under yellow - "false".
Items -> | red | orange | yellow | green |
Controls | | | | |
| | | | | |
V | | | | |
_________|______|________|________|_______|
combo1 |true | false | false |true |
_________|______|________|________|_______|
combo2 |true | false | false |true |
_________|______|________|________|_______|
combo3 |true | false | true |true |
_________|______|________|________|_______|
combo4 |true | true | false |true |
_________|______|________|________|_______|
got the idea?
Now, develop logic that will set those "cells" to false as you click your combos.
In the beginning, all colors will be available to all controls - "true". Then you click one (any) combo. You reserve that control/color cell. Then you build your UI based on this matrix. With each click you have postback and your controls will be re-populated with available colors.
The best part - you will be able to have any number of controls or items for them. Once you run out of items or out of controls, you can't fill controls :o)

How to render a data table with multiple rowspan columns with ListView

I need to display data from a database in a html table. I am currently using a ListView control.
I want the final HTML table to render something like the following, where some rows have a rowspan attribute greater than one. The reason for this is that some fields have several rows of information, but correspond to the same logical entry.
For example:
|---------|---------|----------|----------|
| data | data |data | data |
| | |----------| |
| | |data | |
| | |----------| |
| | |data | |
|---------|---------|----------|----------|
| data | data |data | data |
| | |----------| |
| | |data | |
| | |----------| |
| | |data | |
|---------|---------|----------|----------|
| data | data |data | data |
| | |----------| |
| | |data | |
| | |----------| |
| | |data | |
| | |----------| |
| | |data | |
| | |----------| |
| | |data | |
|---------|---------|----------|----------|
What is the easiest way to accomplish this in ASP.net?
Not too elegant solution for ListView. The main idea is to use Repeater inside the ListView and bind all the sub-data(I mean data from the third column in your example) except the first record to it.
<asp:ListView runat="server" ID="lstData">
<LayoutTemplate>
<table>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td <%# GetRowspan((int)Eval("Data.Length")) %>>
<%# Eval("FirstName") %>
</td>
<td <%# GetRowspan((int)Eval("Data.Length")) %>>
<%# Eval("LastName") %>
</td>
<td>
<%# GetFirst((IEnumerable<string>)Eval("Data")) %>
</td>
<td <%# GetRowspan((int)Eval("Data.Length")) %>>
<%# Eval("Country") %>
</td>
</tr>
<asp:Repeater runat="server"
DataSource=<%# GetRest((IEnumerable<string>)Eval("Data")) %>>
<ItemTemplate>
<tr>
<td>
<%# Container.DataItem %>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:ListView>
and code behind:
public override void DataBind()
{
var item1 = new { FirstName = "John", LastName = "Doe",
Data = new[] { "first", "second", "third" }, Country = "US" };
var item2 = new { FirstName = "Jane", LastName = "Doe",
Data = new string[] { }, Country = "CA" };
var item3 = new { FirstName = "Joe", LastName = "Public",
Data = new[] { "first", "second", "third", "fourth" }, Country = "US" };
lstData.DataSource = new[] { item1, item2, item3 };
lstData.DataBind();
}
protected string GetRowspan(int length)
{
if (length == 0)
return string.Empty;
else
return string.Format("rowspan='{0}'", length);
}
protected string GetFirst(IEnumerable<string> data)
{
return data.FirstOrDefault();
}
protected IEnumerable<string> GetRest(IEnumerable<string> data)
{
if (data.Any())
return data.Skip(1);
else
return Enumerable.Empty<string>();
}
this outputs data in the format you want.
But if the usage of ListView is not necessary you could take a look onto GridView. There is more elegant way to do this by using it - ASP.NET GridView RowSpan using RowCreated Event - How to add Table Dynamic RowSpan with GridView article.
protected override void RenderContents(HtmlTextWriter output)
{
var builder = new StringBuilder();
builder.Append("<table>");
for(int i=0;i<dt1.rows.count;i++)
{
builder.Append("<tr>");
builder.Append("<td>");
builder.Append(dt1.rows[i].ToString());
builder.Append("</td>");
builder.Append("<td>");
builder.Append(dt1.rows[i].ToString());
builder.Append("</td>");
builder.Append("</td>");
builder.Append("<table>");
builder.Append("<tr>");
for(int j=0;i<dt2.rows.count;j++)
{
builder.Append("<td>");builder.Append(dt2.rows[j].ToString());
builder.Append("</td>");
}
builder.Append("</tr>");
builder.Append("</table>");
builder.Append("</tr>");
}
builder.Append("</table>");
output.Write(builder.ToString());
}
assume that dt1 as table1 and dt2 as inner table ...
so approach will help u out ...

Datatable calendar on VisualBasic

I have a request to show a grid similar to a calendar showing on columns the day and on row months.
Something like this
Month |Sun|Mon|Tue|Wed|Thu|Fri|Sat|Sun|Mon|Tue|Wed|Thu|Fri|Sat|Sun|Mon|Tue|Wed|...|Thu|
January | 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| 11|...................| 31|
Febrary | | | | 1| 2| 3| 4| 5| 6| 7|...........................| 29|
...
December| 30| 31| | | | | 1| 2| 3| 4|............................
Is there a way to do this, considering that The Start day of the year must be the real day name, not a constant and this must be generated dynamically
I try this but my idea goes off!
Private Sub GenerateCalendar(ByVal year As Integer)
Dim colsCount As Integer = 3
If Bisiesto(año) Then
colsCount = colsCount + 366
Else
colsCount = colsCount + 365
End If
Dim dtCalendar As New DataTable
dtCalendar.Columns.Add("Mes")
Dim dayMonthYear As Date = New Date(year , 1, 1)
'Showing the distribution of the first month
While dayMonthYear.Year = año And dayMonthYear.Month = 1
Dim dtColumn As DataColumn = New DataColumn()
dtColumn.ColumnName = WeekdayName(Weekday(dayMonthYear)) & dayMonthYear.Day & dayMonthYear.Month
dtColumn.Caption = WeekdayName(Weekday(dayMonthYear))
dtCalendar.Columns.Add(dtColumn)
dayMonthYear = diaMesAño.AddDays(1)
End While
Dim row As DataRow = dtCalendario.NewRow()
'Here I need to distribute the days on its column day
dtCalendario.Rows.Add(row)
wdgCalendario.DataSource = dtCalendar
wdgCalendario.DataBind()
End Sub
Public Function LeapYear(ByVal year As Integer)
Dim isLeapYear As Boolean = False
If year Mod 4 = 0 Then
If (year Mod 100 = 0) And Not (year Mod 400 = 0) Then
isLeapYear = False
Else
isLeapYear = True
End If
Else
isLeapYear = False
End If
Return isLeapYear
End Function
Note: You cannot have duplicate column names in the DataTable, so i have appended the weekday with the number of week in month. But see it for yourself:
Private Function GetCalendarTable(year As Int32) As DataTable
Dim curCulture = System.Globalization.CultureInfo.CurrentCulture
Dim firstYearDate = New Date(year, 1, 1)
Dim currentDate = firstYearDate
Dim tblCalendar = New DataTable
tblCalendar.Columns.Add(New DataColumn("MonthName"))
Dim maxDiff = 0
For m = 1 To 12
'find max difference between first year's weekday and month's first weekday
'if the latter is earlier in the week, it is considered to be in the next week
Dim monthFirstWeekDay = New Date(year, m, 1).DayOfWeek
Dim diff = (7 + (monthFirstWeekDay - firstYearDate.DayOfWeek)) Mod 7
If diff > maxDiff Then
maxDiff = diff
End If
Next
Dim weekDayNum = curCulture.Calendar.GetDaysInMonth(year, 1) + maxDiff
' Create DataColumns with weekday as ColumnsName
For wd = 1 To weekDayNum
Dim weekday = currentDate.ToString("ddd")
Dim weekInMonth = (From col In tblCalendar.Columns.Cast(Of DataColumn)()
Where col.ColumnName Like String.Format("{0} W#", weekday)).Count + 1
Dim columnName = String.Format("{0} W{1}", weekday, weekInMonth)
tblCalendar.Columns.Add(New DataColumn(columnName))
currentDate = currentDate.AddDays(1)
Next
' Create the DataRows(every month)
For m = 1 To 12
Dim daysInMonth = curCulture.Calendar.GetDaysInMonth(year, m)
Dim firstMonthDate = New Date(year, m, 1)
Dim daysBefore = (7 + (firstMonthDate.DayOfWeek - firstYearDate.DayOfWeek)) Mod 7
Dim daysBehind = tblCalendar.Columns.Count - (daysBefore + daysInMonth) - 1
Dim monthDays = From d In Enumerable.Range(1, daysInMonth)
Select New With {.Day = d.ToString}
Dim emptyDaysBefore = From d In Enumerable.Range(1, daysBefore)
Select New With {.Day = ""}
Dim emptyDaysAfter = From d In Enumerable.Range(1, daysBehind)
Select New With {.Day = ""}
Dim monthName = curCulture.DateTimeFormat.GetMonthName(m)
' piece together parts
Dim allFields = ({New With {.Day = monthName}}.
Union(emptyDaysBefore).
Union(monthDays).
Union(emptyDaysAfter).
Select(Function(d) d.Day)).ToArray
tblCalendar.Rows.Add(allFields)
Next
Return tblCalendar
End Function

Resources