Should i set gridview datatable as global variable and use it in crud function?

Yu Fang Chin 1 Reputation point
2022-03-25T01:00:43.72+00:00

Hello,

I am optimizing the code of crud gridview program and i intended to shorter duplicated code into
global variable and function. Below is a part of the result of optimized code but i am not really for sure whether it will cause problem or the writing way is correct or wrong because i am not really familiar with c# before i usually write javascript.

===============================================

private DataTable dt = new DataTable();

protected void InitGridView(DataTable dt)
{
    dt.Columns.Add("ID");
    dt.Columns.Add("UserId");
    dt.Columns.Add("UserName");
    dt.Columns.Add("Date");
    dt.Columns.Add("StartHour");
    dt.Columns.Add("StartMin");
    dt.Columns.Add("EndHour");
    dt.Columns.Add("EndMin");
    dt.Columns.Add("Category");
    dt.Columns.Add("LunchBreak");
    dt.Columns.Add("NightBreak");
    dt.Columns.Add("Hours");
    dt.Columns.Add("DateBelong");
    dt.Columns.Add("TapTime");
    dt.Columns.Add("OtaCategory");
    dt.Columns.Add("Reason");
}

private string date = "";
private float totalHours = 0;

protected void txtDateFooter_SelectedDateChanged(object sender, SelectedDateChangedEventArgs e)
{
    date = e.NewDate.Value.ToString("yyyy/MM/dd");
}

/// <summary>
/// 顯示時欄位初始值
/// </summary>
/// <param name="versionField">欄位集合</param>
public override void SetField(Ede.Uof.WKF.Design.VersionField versionField)
{

    FieldOptional fieldOptional = versionField as FieldOptional;

    if (fieldOptional != null)
    {

        //若有擴充屬性,可以用該屬性存取
        // fieldOptional.ExtensionSetting

        //DataTable dt = new DataTable();

        if (!IsPostBack)
        {
            if (String.IsNullOrEmpty(fieldOptional.FieldValue))
            {
                InitGridView(dt);

                dt.Rows.Add(dt.NewRow());
                Grid1.DataSource = dt;
                Grid1.DataBind();
                Grid1.Rows[0].Cells.Clear();
                Grid1.Rows[0].Cells.Add(new TableCell());
                Grid1.Rows[0].Cells[0].ColumnSpan = dt.Columns.Count;
                Grid1.Rows[0].Cells[0].Text = "尚無資料";
                Grid1.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
            }
            else
            {
                TextBox1.Text = fieldOptional.FieldValue;
                BindGrid();

======================================================

hope to know more about experience of c# developers, thanks!!

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,270 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,276 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Yu Fang Chin 1 Reputation point
    2022-03-28T00:35:27.35+00:00
    protected void Grid1_RowCommand(object sender, GridViewCommandEventArgs e)  
    {  
    
        try  
        {  
            if (e.CommandName.Equals("AddNew"))  
            {  
                int rowIndex = 0;  
    
                //點擊新增按鍵目前是0筆資料的狀態  
                if (String.IsNullOrEmpty(TextBox1.Text))  
                {  
                    InitGridView(dt);  
                }  
                else  
                {  
                    dt = JsonConvert.DeserializeObject<DataTable>(TextBox1.Text);  
                    rowIndex = dt.Rows.Count;  
                }  
    
                //取得輸入的工號後帶出姓名  
                string userName = (Grid1.FooterRow.FindControl("txtUserNameFooter") as TextBox).Text.Trim();  
    
                if (userName == "")  
                {  
                    string userId = (Grid1.FooterRow.FindControl("txtUserIdFooter") as TextBox).Text.Trim();  
    
                    userName = GetUserName(userId);  
                }  
    
                //時數計算  
                string starthourStr = (Grid1.FooterRow.FindControl("txtStartHourFooter") as DropDownList).SelectedValue;  
                string startminStr = (Grid1.FooterRow.FindControl("txtStartMinFooter") as DropDownList).SelectedValue;  
                string endhourStr = (Grid1.FooterRow.FindControl("txtEndHourFooter") as DropDownList).SelectedValue;  
                string endminStr = (Grid1.FooterRow.FindControl("txtEndMinFooter") as DropDownList).SelectedValue;  
                Boolean IsLunchBreak = (Grid1.FooterRow.FindControl("txtLunchBreakFooter") as CheckBox).Checked;  
                Boolean IsNightBreak = (Grid1.FooterRow.FindControl("txtNightBreakFooter") as CheckBox).Checked;  
    
                float totalmin;  
                float totalhours;  
    
                if (starthourStr == "--" || startminStr == "--" || endhourStr == "--" || endminStr == "--")  
                {  
                    totalmin = 0;  
    
                } else  
                {  
                    float starthour = float.Parse(starthourStr);  
                    float startmin = float.Parse(startminStr);  
                    float endhour = float.Parse(endhourStr);  
                    float endmin = float.Parse(endminStr);  
                      
                    totalmin = CalculateTotalMin(starthour, startmin, endhour, endmin, IsLunchBreak, IsNightBreak);  
                }  
    
                //歸屬日期帶出  
                string dateBelong = (Grid1.FooterRow.FindControl("txtDateBelongFooter") as TextBox).Text.Trim();  
    
                if (dateBelong == "")  
                {  
                    dateBelong = date;  
    
                }  
    
                //類別及加班類別  
                string category = (Grid1.FooterRow.FindControl("txtCategoryFooter") as DropDownList).SelectedValue;  
                string otaCategory = (Grid1.FooterRow.FindControl("txtOtaCategoryFooter") as DropDownList).SelectedValue;  
    
    
                if (totalmin % 15 != 0)  
                {  
                    lblErrorMessage.Text = "時間間隔要以15分鐘為單位";  
                }  
                else  
                {  
                    totalhours = (float)Math.Round((totalmin / 60), 2);  
    
                    dt.Rows.Add(new object[] {   
                        rowIndex + 1,  
                        (Grid1.FooterRow.FindControl("txtUserIdFooter") as TextBox).Text.Trim(),  
                        userName,  
                        date,  
                        (Grid1.FooterRow.FindControl("txtStartHourFooter") as DropDownList).SelectedValue,  
                        (Grid1.FooterRow.FindControl("txtStartMinFooter") as DropDownList).SelectedValue,  
                        (Grid1.FooterRow.FindControl("txtEndHourFooter") as DropDownList).SelectedValue,  
                        (Grid1.FooterRow.FindControl("txtEndMinFooter") as DropDownList).SelectedValue,  
                        category,  
                        IsLunchBreak,  
                        IsNightBreak,  
                        totalhours,  
                        dateBelong,  
                        "",  
                        otaCategory,  
                        (Grid1.FooterRow.FindControl("txtReasonFooter") as TextBox).Text.Trim()  
                    });  
    
                    TextBox1.Text = JsonConvert.SerializeObject(dt);  
                    BindGrid();  
    
                    //總時數計算  
                    foreach (DataRow row in dt.Rows)  
                    {  
                        float hours = float.Parse(row.ItemArray[11].ToString());  
                        totalHours += hours;  
                    }  
    
                    totalHour.Text = totalHours.ToString();  
    
                    //新增資料提醒訊息  
                    object[] rowItems = dt.Rows[rowIndex].ItemArray;  
    
                    lblErrorMessage.Text = CRUD_AlertMeassage(rowItems);  
                }  
            }          
        }  
        catch (Exception ex)  
    
        {  
            lblErrorMessage.Text = ex.Message;  
        }  
    }  
    
    protected void Grid1_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        Grid1.EditIndex = e.NewEditIndex;  
        BindGrid();  
    }  
    
    protected void Grid1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
    {  
        Grid1.EditIndex = -1;  
        BindGrid();  
    }  
    
    protected void Grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
    {  
        try  
        {  
            dt = JsonConvert.DeserializeObject<DataTable>(TextBox1.Text);  
    
            //取得輸入的工號後帶出姓名  
            string userName = (Grid1.Rows[e.RowIndex].FindControl("txtUserName") as TextBox).Text.Trim();  
            if (userName == "")  
            {  
                string userId = (Grid1.Rows[e.RowIndex].FindControl("txtUserId") as TextBox).Text.Trim();  
    
                userName = GetUserName(userId);  
            }  
    
            // 時數計算  
            string starthourStr = (Grid1.Rows[e.RowIndex].FindControl("txtStartHour") as DropDownList).SelectedValue;  
            string startminStr = (Grid1.Rows[e.RowIndex].FindControl("txtStartMin") as DropDownList).SelectedValue;  
            string endhourStr = (Grid1.Rows[e.RowIndex].FindControl("txtEndHour") as DropDownList).SelectedValue;  
            string endminStr = (Grid1.Rows[e.RowIndex].FindControl("txtEndMin") as DropDownList).SelectedValue;  
            Boolean IsLunchBreak = (Grid1.Rows[e.RowIndex].FindControl("txtLunchBreak") as CheckBox).Checked;  
            Boolean IsNightBreak = (Grid1.Rows[e.RowIndex].FindControl("txtNightBreak") as CheckBox).Checked;  
    
            float totalmin;  
            float totalhours;  
    
            if (starthourStr == "--" || startminStr == "--" || endhourStr == "--" || endminStr == "--")  
            {  
                totalmin = 0;  
            }  
            else  
            {  
                float starthour = float.Parse(starthourStr);  
                float startmin = float.Parse(startminStr);  
                float endhour = float.Parse(endhourStr);  
                float endmin = float.Parse(endminStr);  
                  
                totalmin = CalculateTotalMin(starthour, startmin, endhour, endmin, IsLunchBreak, IsNightBreak);  
            }  
    
            //歸屬日期帶出  
            string dateBelong = (Grid1.Rows[e.RowIndex].FindControl("txtDateBelong") as TextBox).Text.Trim();  
    
            if (date == "")  
            {  
                date = dt.Rows[e.RowIndex].ItemArray[3].ToString();  
            }  
    
            if (dateBelong == "")  
            {  
                dateBelong = date;  
            }  
    
            if (totalmin % 15 != 0)  
            {  
                lblErrorMessage.Text = "時間間隔要以15分鐘為單位";  
            }  
            else  
            {  
                totalhours = (float)Math.Round((totalmin / 60), 2);  
    
                dt.Rows[e.RowIndex].SetField("UserId", (Grid1.Rows[e.RowIndex].FindControl("txtUserId") as TextBox).Text.Trim());  
                dt.Rows[e.RowIndex].SetField("UserName", userName);  
                dt.Rows[e.RowIndex].SetField("Date", date);  
                dt.Rows[e.RowIndex].SetField("StartHour", (Grid1.Rows[e.RowIndex].FindControl("txtStartHour") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("StartMin", (Grid1.Rows[e.RowIndex].FindControl("txtStartMin") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("EndHour", (Grid1.Rows[e.RowIndex].FindControl("txtEndHour") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("EndMin", (Grid1.Rows[e.RowIndex].FindControl("txtEndMin") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("Category", (Grid1.Rows[e.RowIndex].FindControl("txtCategory") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("LunchBreak", IsLunchBreak);  
                dt.Rows[e.RowIndex].SetField("NightBreak", IsNightBreak);  
                dt.Rows[e.RowIndex].SetField("Hours", totalhours);  
                dt.Rows[e.RowIndex].SetField("DateBelong", dateBelong);  
                dt.Rows[e.RowIndex].SetField("TapTime", "");  
                dt.Rows[e.RowIndex].SetField("OtaCategory", (Grid1.Rows[e.RowIndex].FindControl("txtOtaCategory") as DropDownList).SelectedValue);  
                dt.Rows[e.RowIndex].SetField("Reason", (Grid1.Rows[e.RowIndex].FindControl("txtReason") as TextBox).Text.Trim());  
    
                TextBox1.Text = JsonConvert.SerializeObject(dt);  
                Grid1.EditIndex = -1;  
    
                BindGrid();  
    
                //總時數計算  
                foreach (DataRow row in dt.Rows)  
                {  
                    float hours = float.Parse(row.ItemArray[11].ToString());  
                    totalHours += hours;  
                }  
    
                totalHour.Text = totalHours.ToString();  
    
                // 新增資料提醒訊息  
                object[] rowItems = dt.Rows[e.RowIndex].ItemArray;  
                lblErrorMessage.Text = CRUD_AlertMeassage(rowItems);           
            }  
        }  
        catch (Exception ex)  
        {  
            lblErrorMessage.Text = ex.Message;  
        }  
    }  
    
    protected void Grid1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
    {  
        try  
        {  
            dt = JsonConvert.DeserializeObject<DataTable>(TextBox1.Text);  
            dt.Rows.Remove(dt.Rows[e.RowIndex]);  
            TextBox1.Text = JsonConvert.SerializeObject(dt);  
    
            if (TextBox1.Text == "[]")  
            {  
                TextBox1.Text = "";  
            }  
    
            if (String.IsNullOrEmpty(TextBox1.Text))  
            {  
                dt.Rows.Add(dt.NewRow());  
                Grid1.DataSource = dt;  
                Grid1.DataBind();  
                Grid1.Rows[0].Cells.Clear();  
                Grid1.Rows[0].Cells.Add(new TableCell());  
                Grid1.Rows[0].Cells[0].ColumnSpan = dt.Columns.Count;  
                Grid1.Rows[0].Cells[0].Text = "尚無資料";  
                Grid1.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;  
            }  
            else  
            {  
                BindGrid();  
            }  
    
            lblErrorMessage.Text = "";  
        }  
        catch (Exception ex)  
        {  
            lblErrorMessage.Text = ex.Message;  
        }  
    }  
    

    ============================================

    @Yijing Sun-MSFT
    I used gridview row command event to create crud function like this.


  2. Albert Kallal 4,651 Reputation points
    2022-03-29T17:14:31.31+00:00

    Well, this comes down to how many rows of data?

    I see you are persiting the rows in a text box.

    So, if you have say 30 rows tops? Sure, I think this is ok. If you have more, then probably not a good idea.

    However, you note "global", but I don't really see the data table as a globaal var. But, to make a long story short?

    Variables MUST NOT be assumed to persist during post-backs. During development, it might work while working in Visual Studio, but with multiple users on different pages - and them posting back - hitting the server? No, your variables will NOT persist.

    So, you can serialize into a text box as you done, but you could also use session() (but, caution, since if ONE user opens two web pages, then you start to step on each browser page open.

    Just keep in mind for any button click, and any event code (code behind runs), then the page size and post-back size will increase - since that "data table" is now being shuffled back up to the server, and back down for each button click or post-back. So, for a few rows - maybe tops 20? Sure, I don't see this as a big deal.

    but, for a larger data set? No, not a good idea.

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada

    0 comments No comments