简体   繁体   中英

Unexpected behaviour of dynamic html rendering a table with data via C#

I'm encountering an unfamiliar problem with functionality. I think it has something to do with scope of a loop, and server-side code operations/manipulation when rendering a page.

Say I want to repeat a Table Row - each hosts a text input, rows and their textboxes are rendered with values according to content of DATABASE "binded" Data.

Everything works perfectly until more requirements are added - READONLY Attribute And event Key (javascript small validation task).

Otherwise it does work, alternating rows via two separated strings that I "inject" with string format on a condition of if row count is odd vs even, then I tried to filter some of columns to have a keypress event bound to a js function and another attribute as a string.

If the string is empty, then end part of the element "declaration" will be empty if condition was met, then that string is assigned with value "ReadOnly" and js string is assigned with keypress event "calling a function code".

Here's the code. The situation is weird as style attributes, information of current column, columns names, everything does function as expected but those two READONLY Attribute And event Key (javascript small validation task) that do not.

Render a dynamic Table Code

This is the front code, c# code behind is used mostly (to keep a little code client-side as possible)

`ControlsInteraction.WithTable.Design()`

AND

`ControlsInteraction.WithTable.ExtractData()`

are dealing with dynamic functions of rendering and translation of columns names and values

int count = 0;
bool TblOk = DebugTests.Sesseion.SeSn.Raised(DebugTests.Flag.HT_DB_CPA_Table_init_Complete);
    if (TblOk)
    {
        string TextBxRendr = "";//holds Renderd <TD> base String-code

        string AltrnatBgColor;
        string NoAttribute = "";
        string Js_NumericKprss = "onkeypress=\"return onlN(event)\""
        string ReadOnly = "READONLY";
        var TimesCol = ALLTablesDataSet.Tables[Tbl1.TableName].Columns;
     string DtrawTbl1 = Tbl1.TableName;
     ControlsInteraction.WithTable.Design Tbldz = 
     new ControlsInteraction.WithTable.Design();

     ControlsInteraction.WithTable.ExtractData DtExtrct =
     new ControlsInteraction.WithTable.ExtractData();

        foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DtrawTbl].Rows)
        {

         AltrnatBgColor= Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"),true);
         altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
        Response.Write(string.Format("<tr {0}>",AltrnatBgColor));

                for (int i = 0; i < TimesRow.ItemArray.Length; i++)
                {
                        if (i != (TimesRow.ItemArray.Length - 1))
                        {


                        Js_NumericKprss = "onkeypress=\"return onlN(event)\"";

                   //asking for: current row will Not be read only via its name
                   if (DtExtrct.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.Comments, DtExtrct.DataRowToInt(TimesRow, "RecordNum")))
                                Js_NumericKprss = NoAttribute; // same goes with the other manipulation i've needed to implement on each column
                        TextBxRendr = string.Format(
                        "<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {4} {5} \\></td>", 
                        TimesCol[i], TimesRow["RecordNum"], TimesRow[i], AltrnatBgColor,Js_NumericKprss,ReadOnly
                                                    );

                        }

                        else
                        {
                        TextBxRendr = string.Format(
        "<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{2}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>",
            "img",i + 1, AltrnatBgColor
                            );
                          }


                        Response.Write(TextBxRendr);
                        count++;
                 }

        }
}

Is injected properly and the read only part READONLY Attribute, and event Key - (javascript small validation task)

Either functions on all or none

What am I doing wrong?

answering my own Question aventually answer is

...well everything , including @Patrics Comment Was Wrong

i can just say put good attention to : how to work with DataTable DataRow, DataTable DataColumns and the relations for and foreach variables scope use your visual sudio debugger on every line to check on your codes values

i did not have the time to rename variables but if you need to make a dynamic html table out of a DB table this is the way

   foreach (System.Data.DataRow TimesRow in ALLTablesSet.Tables[DrawTbl].Rows)
    {
        recordNum = RDE.DataRowToInt(TimesRow, "RecordNum");
        AltBgCol = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), true);
        altBgColOnly = Tbldz.RowsBGColorAlternate(RDE.DataRowToInt(TimesRow, "RecordNum"), false);
        Response.Write(string.Format("<tr {0}>", AltBgCol));
        for (int i = 0; i < TimesRow.ItemArray.Length; i++)
        {


            if (i != (TimesRow.ItemArray.Length - 1))
            {
                Js_NumericKprss = "onkeypress=\"return onlN(event)\""; ReadOnly = "";
                if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Comments, i))
                {
                    Js_NumericKprss = ""; ReadOnly = "";
                }

                else if (RDE.CurrRowIs(TimesRow, HentalDBSchema.HTDB_Cols.TblTimeCPAReport.Fines, i)
                 || RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.PhoneExpences, i)
                 || RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerDay, i)
                 || RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.SalaryPerMonth, i)
                 || RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TotalGrossWages, i)
                 || RDE.CurrRowIs(TimesRow, MyDBSchema.DBs_Cols.TblCPAReport.TravelFee, i))
                {
                    ReadOnly = "";
                    Js_NumericKprss = "onkeypress=\"return onlN(event)\"";
                }
                else
                    ReadOnly = "READONLY";

                TxtRndr = string.Format("<td><input type='text' id=\"{0}_{1}\" value=\"{2} \" style=\"width:50px;{3} border:none; \" class=\"RepTblDataTDs\" {5} {6} \\></td>{4}", TimesCol[i], TimesRow["RecordNum"], TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t", Js_NumericKprss, ReadOnly);
            }

            else
            {
                TxtRndr = string.Format("<td><input type='image' id=\"{0}_{1}\" src=\"images/Save.png\" style=\"width:25px;{3}\" style=\"width:25px\" onclick=\"UbpdateTblCPA(this, {1});\" /></td>{4}", "imgBut", i + 1, TimesRow[i], altBgColOnly, Environment.NewLine + "\t\t\t");
            }


            Response.Write(TxtRndr);




            count++;
        }

    }

i am adding all researches i have made to be more easy on the data extraction and some more methods i have worked on so if u like to use it feel free to ...

    public class ControlsInteraction
    {
        public class WithDDL
        {
            public class GetSelVal
            {
                public string AsString(DropDownList DDLToCollectValusFrom)
                {

                    return DDLToCollectValusFrom.SelectedValue;
                }
                public int AsInt(DropDownList DDLToCollectValusFrom)
                { 
                    if(DDLToCollectValusFrom.SelectedValue != null)
                    return Convert.ToInt32(DDLToCollectValusFrom.SelectedValue);
                    return 666;
                }
            }
            public List<string> GetListItems_Values(DropDownList DDLToCollectValusFrom)
            {
                List<string> LST_DDLValues = new List<string>();
                foreach (ListItem item in DDLToCollectValusFrom.Items)
                {
                    LST_DDLValues.Add(item.Value);


                }
                return LST_DDLValues;
            }
            public List<string> GetListItems_Text(DropDownList DDLToCollectTextFrom)
            {
                List<string> LST_DDLTEXT = new List<string>();
                foreach (ListItem item in DDLToCollectTextFrom.Items)
                {
                    LST_DDLTEXT.Add(item.Text);


                }
                return LST_DDLTEXT;
            }
        }
        public static class WithPlcHldr
        {
            public static void AddCtrl(PlaceHolder PlcHldrID, Control CntrID)
            {
                PlcHldrID.Controls.Add(CntrID);
            }
        }
        public class WithTable
        {
            public class Design
            {
                public string RowsBGColorAlternate(int RowCounter, bool AddWithStyleAsStandAlone = false)
                {
                    string BgCol = ""; bool bgclaltrnator;
                    if (RowCounter > 0)
                    {
                        RowCounter++;
                        bgclaltrnator = (RowCounter % 2) == 0;
                        if (bgclaltrnator)
                            BgCol = "#70878F";
                        else BgCol = "#E6E6B8";
                    }
                    if (AddWithStyleAsStandAlone)
                    return string.Format("style=\"background-color:{0};\"", BgCol);
                    return string.Format("background-color:{0};", BgCol);
                }
            }
            public class ExtractData
            {
                public string ColumnValueFromCurrRow(DataRow DtRow, string RequestedColName)
               {
                    return "";
                }
                public string DataRows_ColumnToString(DataRow Data_RowToActOn, string keyColName)
                {
                    var tmp = Data_RowToActOn[keyColName];
                    return Data_RowToActOn[keyColName].ToString();

                }
                public int DataRowToInt(DataRow Data_RowToActOn, string keyColName)
                {
                    string tmp = Data_RowToActOn[keyColName].ToString();
                    return Convert.ToInt32(tmp);

                }
                public bool CurrColumnIs(DataColumn Data_RowToQuestion, string ColumnName)
                {
                    string tmp = Data_RowToQuestion.ToString();
                    return tmp == ColumnName;
                }
                public bool CurrRowIs(DataRow Data_RowToQuestion, string RowName, int CurrIndex)
                {
                    string ColsName = Data_RowToQuestion.Table.Columns[CurrIndex].ToString();
                    return ColsName == RowName;
                    //this is curent value - by index 

                    //string currentColumn = Data_RowToQuestion.ItemArray[CurrIndex].ToString();

                }
            }

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM