Datagrid contenente tabella a runtime

sabato 14 luglio 2007 - 08.33

terrix77 Profilo | Newbie

Salve a tutti, da qualche tempo ho un gran bel problema che cercherò di spiegare, e ne sarò davvero grato a chi me lo risolvesse.

Ho una pagina ASP.NET 2.0 così strutturata: un datagrid contenente delle colonne di tipo itemtemplate (1 colonna immagine- 2 colonna label, 3 colonna placeholder - 4 colonna label) i cui valori sono letti da database e la cui logica è piazzata è tutta piazzata nell'evento ONITEMDATABOUND, e fin qui nessun problema. Sempre nel medesimo evento costruisco a runtime una tabella (3 colonna del datagrid di tipo itemtemplate contenete un placeholder) avente il numero di righe e il numero di colonne dipendenti da due query differenti; sempre all'interno di tale tabella le celle contengono dei textbox creati anch'essi runtime secondo alcune condizioni dettate dalle query precedenti. Tale tabella ASP.NET è aggiunta runtime al placeholder, il quale come già detto, è piazzato nella 3 colonna itemtemplate del datagrid, ed anche fin qui nessun problema.

Adesso arrivano i seri problemi.
Il primo problema nasce dal fatto che tali textbox, contenuti nella tabella asp.net e costruiti a runtime devono, all'avvio della pagina, essere valorizzati da valori prelevati da una tabella sql (che non so come strutturare perchè come detto in precedenza il numero di textbox è variabile in funzione delle query precedenti) ed inoltre non so che logica scrivere per effettuare tale operazione e dove piazzarla (mi viene da pensare nell'ONITEMDATABOUND del datagrid).

Il secondo problema nasce quando devo andare ad aggiornare il database contenente i valori dei textbox eventualmente modificati dall'utente tramite un click di un pulsante.

E' una struttura abbastanza articolata, infatti sono arenato e non so come proseguire.
AIUTO

AlexDotNet Profilo | Newbie

Per quanto riguarda il punto 1, e, cioè andare a prendere la sottotabella correlata in base alla riga, basta referenziare
ctype(e.item.DataItem,DataRowView)
quindi ad ogni riga hai referenziato la riga su cu idevi prendere i records correlati.
Per quanto riguarda il punto 2 basta aggiungere nel codice HTML oltre a Item anche EditItem ....
Fammi sapere se questa strada ti è chiara.
Ciao Alex

terrix77 Profilo | Newbie

Ciao alex, intanto ti ringrazio per la celerità della tua risposta e ti dico inoltre che in ben 8 forum in cui ho postato il quesito nessuno ha trovato la soluzione al mio problema. La tua strada mi sembra ingegnosa ma non ho capito bene come realizzarla programmaticamente. Ti posto l'intero code e il code-behind della mia pagina magari sono vicino alla soluzione e mi manca quel piccolo passo per completarla:

<asp:datagrid id="GridCarrello" CssClass="Carrello" runat="server" HorizontalAlign="Center" Width="100%" ShowFooter="true"
OnItemDataBound="GridCarrello_ItemDataBound" AutoGenerateColumns="False" CellPadding="3" BorderWidth="1px" BorderStyle="NotSet">
<HeaderStyle CssClass="CarrelloIntestazione" />
<Columns>
<asp:BoundColumn DataField="ProductId" Visible="false" />
<asp:TemplateColumn ItemStyle-Width="20%" HeaderText="ARTICOLO">
<ItemTemplate>
<asp:label id="productname" runat="server" text='<%# DataBinder.Eval(Container, "DataItem.productname") %>' />
<a id="LnkPreview" runat="server" class="highslide" onclick="javascript:return hs.expand(this, {captionId: 'caption1'})">
<img src="" id="ImgPreview" runat="server" alt="Clicca per zoomare il modello" />
</a>
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn ItemStyle-Width="65%" HeaderText="COLORE/TAGLIA">
<ItemTemplate>
<asp:PlaceHolder id="PlhVarianti" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>

<asp:TemplateColumn ItemStyle-Width="5%" HeaderText="QUANTITA'">
<ItemTemplate>
<asp:TextBox id="Quantity" CssClass="InputClass" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.quantity") %>' Columns="3">
</asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox id="QuantityEdit" CssClass="InputClass" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.quantity") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn ItemStyle-Width="5%" DataField="UnitPrice" HeaderText="PREZZO" />
<asp:ButtonColumn ItemStyle-Width="5%" Text="elimina" CommandName="Delete" />
</Columns>
</asp:datagrid>

<asp:label id="Label3" runat="server" Font-Bold="True">Total Amount :</asp:label><asp:label id="lblAmt" runat="server" Font-Bold="True"></asp:label></TD>
<asp:button id="Button1" runat="server" Text="Recalculate"></asp:button>



e poi



using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Carrello : System.Web.UI.Page
{
string IDUser;

override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.GridCarrello.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.GridCarrello_DeleteCommand);
//this.GridCarrello.SelectedIndexChanged += new System.EventHandler(this.GridCarrello_SelectedIndexChanged);
this.Button1.Click += new System.EventHandler(this.Button1_Click);
//this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Load += new System.EventHandler(this.Page_Load);
}

protected void Page_PreRender(object sender, EventArgs e)
{

}

protected void Page_Load(object sender, EventArgs e)
{
IDUser = SecurityManager.SecurityManager.GetUserID(User.Identity.Name.ToString());

if (!Page.IsPostBack)
{
FillCartFromDb();
}
}

private void FillCartFromDb()
{
DataSet ds = ShoppingCart.CShoppingCart.GetAll(IDUser);
GridCarrello.DataSource = ds;
GridCarrello.DataBind();
Button1_Click(null, null);
}

private void Button1_Click(object sender, System.EventArgs e)
{
decimal total = 0;

try
{
foreach (DataGridItem dgi in GridCarrello.Items)
{
if (dgi.ItemType == ListItemType.Item || dgi.ItemType == ListItemType.AlternatingItem)
{
TextBox t = (TextBox)dgi.Cells[3].Controls[1];
int quantity = int.Parse(t.Text);
decimal unitprice = Decimal.Parse(dgi.Cells[4].Text);
total = total + (unitprice * quantity);

ShoppingCart.CShoppingCart.UpdateQuantity(Session.SessionID, int.Parse(dgi.Cells[0].Text), quantity, IDUser);
}
}
}
catch
{
}

lblAmt.Text = total.ToString();
FillCartFromDb();
}

public void GridCarrello_ItemDataBound(object sender, DataGridItemEventArgs e)
{
DataRow Row;
string UID;
string idproduct;
string idshoppingcart;

HtmlImage ImgPreview;
HtmlAnchor LnkPreview;
PlaceHolder PlhVarianti;

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem || e.Item.ItemType == ListItemType.EditItem)
{
//CONFIG DATAGRID STYLE
//e.Item.Attributes.Add("onmouseover", "this.style.backgroundColor='#DDEEFF'");
//e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
//e.Item.Style["cursor"] = "hand";

Row = ((DataRowView)(e.Item.DataItem)).Row;
UID = Row["IDShoppingCart"].ToString();
idproduct = Row["ProductId"].ToString();
idshoppingcart = Row["IDShoppingCart"].ToString();

ImgPreview = ((HtmlImage)(e.Item.Cells[1].FindControl("ImgPreview")));
LnkPreview = ((HtmlAnchor)(e.Item.Cells[1].FindControl("LnkPreview")));
PlhVarianti = ((PlaceHolder)(e.Item.Cells[1].FindControl("PlhVarianti")));

//RECUPERO L'IMMAGINE DEL MODELLO
SqlConnection conn;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectImgDefault = "SELECT * FROM V_PRODUCT_MEDIA WHERE IDProduct = " + idproduct + "";
SqlCommand CmdImgDefault = new SqlCommand(SelectImgDefault, conn);
conn.Open();
SqlDataReader ObjDRImgDefault = CmdImgDefault.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

if (ObjDRImgDefault.Read())
{
System.Drawing.Image realImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])ObjDRImgDefault["Thumbnail"]));
int altezza = realImage.Height * Convert.ToInt32(ConfigurationManager.AppSettings["FattoreScala"]) / 100;
int lunghezza = realImage.Width * Convert.ToInt32(ConfigurationManager.AppSettings["FattoreScala"]) / 100;

ImgPreview.Height = altezza;
ImgPreview.Width = lunghezza;
ImgPreview.Src = "Image.aspx?idproduct=" + idproduct + "&IdImage=" + ObjDRImgDefault["IdImage"].ToString() + "&ScaleFactor=" + ConfigurationManager.AppSettings["FattoreScalaDefault"] + "";
LnkPreview.HRef = "Image.aspx?idproduct=" + idproduct + "&IdImage=" + ObjDRImgDefault["IdImage"].ToString() + "&ScaleFactor=" + ConfigurationManager.AppSettings["FattoreScalaDefault"] + "";
}

ObjDRImgDefault.Close();
conn.Close();

//**********************************************************
//COSTRUZIONE MATRICE VARIANTI
//**********************************************************
Table VariantTable = new System.Web.UI.WebControls.Table();
VariantTable.BorderWidth = 1;
VariantTable.CssClass = "Varianti";
VariantTable.GridLines = GridLines.Both;
VariantTable.CellPadding = 0;
VariantTable.CellSpacing = 0;
VariantTable.Width = Unit.Percentage(98);

//REPERIMENTO DEI COLORI
SqlConnection conn_color;
conn_color = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectColor = "SELECT StyleAssociations.Product AS IDProduct, StyleAssociations.Color AS IDColor, Colors.Name, Colors.Red, Colors.Green, Colors.Blue FROM StyleAssociations INNER JOIN Colors ON StyleAssociations.Color = Colors.Id GROUP BY StyleAssociations.Color, StyleAssociations.Product, Colors.Name, Colors.Red, Colors.Green, Colors.Blue HAVING (StyleAssociations.Product = " + idproduct + ")";
SqlCommand CmdColor = new SqlCommand(SelectColor, conn_color);
conn_color.Open();
SqlDataReader ObjDRColor = CmdColor.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

TableRow tr = new TableRow();

//PRIMA CELLA VUOTA
TableCell tdv = new TableCell();
tdv.Width = Unit.Percentage(10);
tdv.Text = "";
tdv.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(tdv);

ArrayList ListColor = new ArrayList();

while (ObjDRColor.Read())
{
ListColor.Add(ObjDRColor["IDColor"].ToString());
TableCell td = new TableCell();
td.Width = Unit.Percentage(10);
td.Text = /*ObjDRColor["Name"].ToString().ToLower() + */ "<div style='background-color: " + System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(Int32.Parse(ObjDRColor["Red"].ToString()), Int32.Parse(ObjDRColor["Green"].ToString()), Int32.Parse(ObjDRColor["Blue"].ToString()))) + "; width: 10px; height: 10px;'></div>";
td.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(td);
}
ObjDRColor.Close();
conn_color.Close();

//INTESTAZIONE DEI TOTALI DELLE QUANTITA'
TableCell tdIntTotal = new TableCell();
tdIntTotal.Width = Unit.Percentage(10);
tdIntTotal.Text = "TOTALE";
tdIntTotal.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(tdIntTotal);

//AGGIUNGO LE CELLE COLORI ALLA TABELLA
VariantTable.Rows.Add(tr);

//REPERIMENTO DELLE TAGLIE
SqlConnection conn_size;
conn_size = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectSize = "SELECT StyleAssociations.Product AS IDProduct, StyleAssociations.Size AS IDSize, Sizes.Name AS Size FROM StyleAssociations INNER JOIN Sizes ON StyleAssociations.Size = Sizes.Id GROUP BY StyleAssociations.Product, StyleAssociations.Size, Sizes.Name HAVING (StyleAssociations.Product = " + idproduct + ")";
SqlCommand CmdSize = new SqlCommand(SelectSize, conn_size);
conn_size.Open();
SqlDataReader ObjDRSize = CmdSize.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (ObjDRSize.Read())
{
TableRow trsize = new TableRow();
TableCell tdsize = new TableCell();
tdsize.Width = Unit.Percentage(10);
tdsize.Text = ObjDRSize["Size"].ToString().ToUpper();
tdsize.VerticalAlign = VerticalAlign.Middle;
trsize.Cells.Add(tdsize);

//REPERIMENTO DELLE QUANTITA'
for (int j = 0; j < ListColor.Count; j++)
{
TableCell tdquantity = new TableCell();
tdquantity.Width = Unit.Percentage(10);

SqlConnection conn_quantity;
conn_quantity = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectQuantity = "SELECT * FROM STYLEASSOCIATIONS WHERE Product = " + idproduct + " AND COLOR=" + ListColor[j].ToString() + " AND SIZE=" + ObjDRSize["IDSize"].ToString() + "";
SqlCommand CmdQuantity = new SqlCommand(SelectQuantity, conn_quantity);
conn_quantity.Open();
SqlDataReader ObjDRQuantity = CmdQuantity.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (ObjDRQuantity.Read())
{
if (ObjDRQuantity["Quantity"] != DBNull.Value)
{

tdquantity.Text = ObjDRQuantity["Quantity"].ToString(); /* + "<input type=text size=3 class=InputClass>"; */

//TODO: DA PROVARE
ArrayList ListQuantityCode = new ArrayList();
string QuantityCode = "";
SqlConnection connQuantityCode;
connQuantityCode = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectQuantityCode = "SELECT ASPNETQUANTITYCODE FROM SHOPPINGCART_PRODUCTS WHERE IDShoppingCart = " + idshoppingcart + "";
SqlCommand CmdQuantityCode = new SqlCommand(SelectQuantityCode, connQuantityCode);
connQuantityCode.Open();
SqlDataReader ObjDRQuantityCode = CmdQuantityCode.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

if (ObjDRQuantityCode.Read())
{
if (ObjDRQuantityCode["ASPNETQUANTITYCODE"] != DBNull.Value)
{
ListQuantityCode.Add(ObjDRQuantityCode["ASPNETQUANTITYCODE"].ToString());
}
}
ObjDRQuantityCode.Close();
connQuantityCode.Close();


TextBox qty = new TextBox();
qty.ID = "Crr_" + ListColor[j].ToString() + "_" + ObjDRSize["IDSize"].ToString();

//LOGICA DI SPLIT PER PASSARE AI TEXTBOX RUNTIME LA QUANTITA




qty.Text = "";
qty.CssClass = "InputClass";
qty.Width = 30;
tdquantity.Controls.Add(qty);


}
else
{
tdquantity.Text = "";
}
}
ObjDRQuantity.Close();
conn_quantity.Close();

tdquantity.VerticalAlign = VerticalAlign.Middle;

trsize.Cells.Add(tdquantity);
}

//CALCOLO TOTALI DELLE QUANTITA' PER COLOR/SIZE
TableCell tdtotal = new TableCell();
tdtotal.Width = Unit.Percentage(10);

int TotaleQuantita = 0;
for (int i = 0; i < ListColor.Count; i++)
{
SqlConnection conn_totalquantity;
conn_totalquantity = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectTotalQuantity = "SELECT * FROM STYLEASSOCIATIONS WHERE Product = " + idproduct + " AND COLOR=" + ListColor[i].ToString() + " AND SIZE=" + ObjDRSize["IDSize"].ToString() + "";
SqlCommand CmdTotalQuantity = new SqlCommand(SelectTotalQuantity, conn_totalquantity);
conn_totalquantity.Open();
SqlDataReader ObjDRTotalQuantity = CmdTotalQuantity.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (ObjDRTotalQuantity.Read())
{
if (ObjDRTotalQuantity["Quantity"] != DBNull.Value)
{
TotaleQuantita += Int32.Parse(ObjDRTotalQuantity["Quantity"].ToString());
tdtotal.Text = TotaleQuantita.ToString();
}
}
ObjDRTotalQuantity.Close();
conn_totalquantity.Close();
}

tdtotal.VerticalAlign = VerticalAlign.Middle;
//END TOTALI DELLE QUANTITA' PER COLOR/SIZE

trsize.Cells.Add(tdtotal);

//AGGIUNGO LE CELLE SIZE ALLA TABELLA
VariantTable.Rows.Add(trsize);
}
ObjDRSize.Close();
conn_size.Close();

//AGGIUNGO AL PLACEHOLDER LA TABELLA VARIANTI
PlhVarianti.Controls.Add(VariantTable);
//**********************************************************
//END COSTRUZIONE MATRICE VARIANTI
//**********************************************************


}
}

private void GridCarrello_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
ShoppingCart.CShoppingCart.DeleteItem(Session.SessionID, int.Parse(e.Item.Cells[0].Text), IDUser);
FillCartFromDb();
}


In pratica le operazioni che devo effettuare sono in sequenza: 1) visualizzare ad ogni riga del datagrid la tabella costruita a runtime (lo fa ma al postback della pagina sparisce) 2) al click del pulsante salvare in una apposita tabella sql i riferimenti (gli ID) delle tabelle del datagrid per riga.

Spero di essere stato chiaro e spero che mi tu mi possa illuminare su questo che ormai più di un problema è diventato per me un arcano, ciao e grazie in anticipo

AlexDotNet Profilo | Newbie

Purtroppo il tempo di leggermi il tuo codice non ce l'ho però ti scrivo in pseudo codice cosa dovresti fare(visto che uso VB e non
C# e i repeater anzichè i gridview)

dentro i repeater usa questi due nodiu principali:
ItemTemplate e AlternatingItemTemplate
<ItemTemplate>
<tr>
<td><a href='?details_2=<%# Eval("ID_Riga_Principale") %>'><%# Eval("ID_Riga_Principale") %></a></td>
<td><%#Eval("TotaleAnnullate")%></td>
<td><%# String.Format("{0:##.00}", Eval("TotaleImpAnnullate"))%> €.</td>
</tr>
<tr id=<%# Eval("ID_Riga_Principale") %>>
<td colspan="3">
<asp:rptDetails .... OnItemDataBound="AssociadatiSecondari">
............
</asp:rptDetails>
</td>
<tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td><a href='?details_2=<%# Eval("ID_Riga_Principale") %>'><%# Eval("ID_Riga_Principale") %></a></td>
<td><%#Eval("TotaleAnnullate")%></td>
<td><%# String.Format("{0:##.00}", Eval("TotaleImpAnnullate"))%> €.</td>
</tr>
<tr id=<%# Eval("ID_Riga_Principale") %>>
<td colspan="3">
<asp:rptDetails .... OnItemDataBound="AssociadatiSecondari">
............
</asp:rptDetails>
</td>
<tr>
</AlternatingItemTemplate>
COn JS puoi fare anche l'effetto di far apparire le irghe di dettaglio referneziando <%# Eval("ID_Riga_Principale") %>

nella prima cella --> <a href='?details_2=<%# Eval("ID_Riga_Principale") %>'><%# Eval("ID_Riga_Principale") %></a>
questo coll. serve a madare una querystring per refreshare la pagina.
anche se è preferibile usare al posto di un coll <A> un CommandButton in questo modo fai un post back della pagina
e conservi il viewstate

sul DataBaound del repeater principale fai questo
Private Sub rptPrinciaple_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptScommesse.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim dr As DataRowView = DirectCast(e.Item.DataItem, DataRowView)
' qui dentro chiamerai il databinding del repeater rptDetails
' e il gioco è fatto


P.S.
Mi stavo dimenticando del secondo punto
con I repeater non è intuitivo come con i DataGrid però basta assciaore un commandName al pulsante (per aggiornare) e come commandArgument per ritrovare il la riga in questione lo puoi fare dentro Private Sub rptPrinciaple_ItemDataBound.

Lo so ...., non è facile ma neanche la richiesta è tanto semplice .... anche se non impossibile

terrix77 Profilo | Newbie

Ciao Alex, grazie ancora per la tua risposta, sei troppo gentile. La soluzione dei controlli annidati è ottima ma ritengo non applicabile (certamente per mia ignoranza) al mio contesto perchè la tabella ASP.NET in questione deve dipendere necessariamente da 3 query che mi danno nell'ordine: intestazione (1 query), prima colonna (2 query), corpo della tabella (3 query dipendente dagli ID delle due precedenti), in pratica si tratta di una struttura matriciale. Come puoi vedere giù ho costruito tale struttura con la tabella a runtime (non riuscendo a capire come fare con controlli tradizionali ASP.NET).

In pratica, come puoi vedere giù, costruisco tale struttura tramite una tabella (non sapendo mettere in pratica altri controlli ASP.NET che facciano al caso mio) in cui in certe celle vengono costruiti a runtime i textbox, e questo funziona alla perfezione; il mio problema principale consiste
nel salvataggio
(quando inputo i valori nei textbox)
e recupero
(quando accedo alla pagina) dei valori di tali textbox in quanto non conosco a priori quanti textbox verranno creati e come strutturare la tabella sql per effettuare le suddette operazioni. Per ridurre la lettura del codice ti posto parte del codice funzionante (contenuto nell'evento ONITEMDATABOUND del datagrid).

//**********************************************************
//COSTRUZIONE MATRICE VARIANTI
//**********************************************************
Table VariantTable = new System.Web.UI.WebControls.Table();
VariantTable.BorderWidth = 1;
VariantTable.CssClass = "Varianti";
VariantTable.GridLines = GridLines.Both;
VariantTable.CellPadding = 0;
VariantTable.CellSpacing = 0;
VariantTable.Width = Unit.Percentage(98);

//REPERIMENTO DEI COLORI
SqlConnection conn_color;
conn_color = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectColor = "SELECT StyleAssociations.Product AS IDProduct, StyleAssociations.Color AS IDColor, Colors.Name, Colors.Red, Colors.Green, Colors.Blue FROM StyleAssociations INNER JOIN Colors ON StyleAssociations.Color = Colors.Id GROUP BY StyleAssociations.Color, StyleAssociations.Product, Colors.Name, Colors.Red, Colors.Green, Colors.Blue HAVING (StyleAssociations.Product = " + idproduct + ")";
SqlCommand CmdColor = new SqlCommand(SelectColor, conn_color);
conn_color.Open();
SqlDataReader ObjDRColor = CmdColor.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

TableRow tr = new TableRow();

//PRIMA CELLA VUOTA
TableCell tdv = new TableCell();
tdv.Width = Unit.Percentage(10);
tdv.Text = "";
tdv.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(tdv);

ArrayList ListColor = new ArrayList();

while (ObjDRColor.Read())
{
ListColor.Add(ObjDRColor["IDColor"].ToString());
TableCell td = new TableCell();
td.Width = Unit.Percentage(10);
td.Text = /*ObjDRColor["Name"].ToString().ToLower() + */ "<div style='background-color: " + System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(Int32.Parse(ObjDRColor["Red"].ToString()), Int32.Parse(ObjDRColor["Green"].ToString()), Int32.Parse(ObjDRColor["Blue"].ToString()))) + "; width: 10px; height: 10px;'></div>";
td.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(td);
}
ObjDRColor.Close();
conn_color.Close();

//INTESTAZIONE DEI TOTALI DELLE QUANTITA'
TableCell tdIntTotal = new TableCell();
tdIntTotal.Width = Unit.Percentage(10);
tdIntTotal.Text = "TOTALE";
tdIntTotal.VerticalAlign = VerticalAlign.Middle;
tr.Cells.Add(tdIntTotal);

//AGGIUNGO LE CELLE COLORI ALLA TABELLA
VariantTable.Rows.Add(tr);

//REPERIMENTO DELLE TAGLIE
SqlConnection conn_size;
conn_size = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectSize = "SELECT StyleAssociations.Product AS IDProduct, StyleAssociations.Size AS IDSize, Sizes.Name AS Size FROM StyleAssociations INNER JOIN Sizes ON StyleAssociations.Size = Sizes.Id GROUP BY StyleAssociations.Product, StyleAssociations.Size, Sizes.Name HAVING (StyleAssociations.Product = " + idproduct + ")";
SqlCommand CmdSize = new SqlCommand(SelectSize, conn_size);
conn_size.Open();
SqlDataReader ObjDRSize = CmdSize.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (ObjDRSize.Read())
{
TableRow trsize = new TableRow();
TableCell tdsize = new TableCell();
tdsize.Width = Unit.Percentage(10);
tdsize.Text = ObjDRSize["Size"].ToString().ToUpper();
tdsize.VerticalAlign = VerticalAlign.Middle;
trsize.Cells.Add(tdsize);

//REPERIMENTO DELLE QUANTITA'
for (int j = 0; j < ListColor.Count; j++)
{
TableCell tdquantity = new TableCell();
tdquantity.Width = Unit.Percentage(10);

SqlConnection conn_quantity;
conn_quantity = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectQuantity = "SELECT * FROM STYLEASSOCIATIONS WHERE Product = " + idproduct + " AND COLOR=" + ListColor[j].ToString() + " AND SIZE=" + ObjDRSize["IDSize"].ToString() + "";
SqlCommand CmdQuantity = new SqlCommand(SelectQuantity, conn_quantity);
conn_quantity.Open();
SqlDataReader ObjDRQuantity = CmdQuantity.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (ObjDRQuantity.Read())
{
if (ObjDRQuantity["Quantity"] != DBNull.Value)
{

tdquantity.Text = ObjDRQuantity["Quantity"].ToString(); /* + "<input type=text size=3 class=InputClass>"; */

//TODO: DA PROVARE
ArrayList ListQuantityCode = new ArrayList();
string QuantityCode = "";
SqlConnection connQuantityCode;
connQuantityCode = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectQuantityCode = "SELECT ASPNETQUANTITYCODE FROM SHOPPINGCART_PRODUCTS WHERE IDShoppingCart = " + idshoppingcart + "";
SqlCommand CmdQuantityCode = new SqlCommand(SelectQuantityCode, connQuantityCode);
connQuantityCode.Open();
SqlDataReader ObjDRQuantityCode = CmdQuantityCode.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

if (ObjDRQuantityCode.Read())
{
if (ObjDRQuantityCode["ASPNETQUANTITYCODE"] != DBNull.Value)
{
ListQuantityCode.Add(ObjDRQuantityCode["ASPNETQUANTITYCODE"].ToString());
}
}
ObjDRQuantityCode.Close();
connQuantityCode.Close();


TextBox qty = new TextBox();
qty.ID = "Crr_" + ListColor[j].ToString() + "_" + ObjDRSize["IDSize"].ToString();

//LOGICA DI SPLIT PER PASSARE AI TEXTBOX RUNTIME LA QUANTITA




qty.Text = "";
qty.CssClass = "InputClass";
qty.Width = 30;
tdquantity.Controls.Add(qty);


}
else
{
tdquantity.Text = "";
}
}
ObjDRQuantity.Close();
conn_quantity.Close();

tdquantity.VerticalAlign = VerticalAlign.Middle;

trsize.Cells.Add(tdquantity);
}

//CALCOLO TOTALI DELLE QUANTITA' PER COLOR/SIZE
TableCell tdtotal = new TableCell();
tdtotal.Width = Unit.Percentage(10);

int TotaleQuantita = 0;
for (int i = 0; i < ListColor.Count; i++)
{
SqlConnection conn_totalquantity;
conn_totalquantity = new SqlConnection(ConfigurationManager.ConnectionStrings["WFDB"].ConnectionString);
string SelectTotalQuantity = "SELECT * FROM STYLEASSOCIATIONS WHERE Product = " + idproduct + " AND COLOR=" + ListColor[i].ToString() + " AND SIZE=" + ObjDRSize["IDSize"].ToString() + "";
SqlCommand CmdTotalQuantity = new SqlCommand(SelectTotalQuantity, conn_totalquantity);
conn_totalquantity.Open();
SqlDataReader ObjDRTotalQuantity = CmdTotalQuantity.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
while (ObjDRTotalQuantity.Read())
{
if (ObjDRTotalQuantity["Quantity"] != DBNull.Value)
{
TotaleQuantita += Int32.Parse(ObjDRTotalQuantity["Quantity"].ToString());
tdtotal.Text = TotaleQuantita.ToString();
}
}
ObjDRTotalQuantity.Close();
conn_totalquantity.Close();
}

tdtotal.VerticalAlign = VerticalAlign.Middle;
//END TOTALI DELLE QUANTITA' PER COLOR/SIZE

trsize.Cells.Add(tdtotal);

//AGGIUNGO LE CELLE SIZE ALLA TABELLA
VariantTable.Rows.Add(trsize);
}
ObjDRSize.Close();
conn_size.Close();

//AGGIUNGO AL PLACEHOLDER LA TABELLA VARIANTI
PlhVarianti.Controls.Add(VariantTable);
//**********************************************************
//END COSTRUZIONE MATRICE VARIANTI
//**********************************************************

Capisco che il problema non è di facile soluzione ma tento di capire se sia insormontabile o meno. TI ringrazio in anticipo, ciao
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5