By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,640 Members | 1,363 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,640 IT Pros & Developers. It's quick & easy.

How to get value in dynamic control in gridview when postback?

P: 1
first time i create dynamic column in code behind and add it into gridview and my problem is i want to get value of textBox in TemplateField of GridViewColumn after postback to server and i want to get this value to insert data to database.
Please look and focus this syntax "<----" at InsertIncentiveScore() Function or text underline

Client code
Expand|Select|Wrap|Line Numbers
  1. <asp:GridView ID="grdInCenScore" runat="server" AutoGenerateColumns="False" BCellPadding="2"
  2.                                             Width="1024px" AllowPaging="True" EmptyDataText="No Data" ShowHeaderWhenEmpty="True"
  3.                                             CssClass="DataGrid" ShowHeader="False">
  4.                                             <RowStyle CssClass="DataGridItem" Height="28px" />
  5.                                             <PagerStyle HorizontalAlign="Left" CssClass="pager" />
  6.                                             <HeaderStyle CssClass="DataGridHeader" />
  7.                                             <AlternatingRowStyle CssClass="DataGridAlternating" />
  8.                                             <Columns>
  9.                                                 <asp:BoundField HeaderText="No" DataField="No">
  10.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  11.                                                     <ItemStyle HorizontalAlign="Center" Width="30px" />
  12.                                                 </asp:BoundField>
  13.                                                 <asp:BoundField HeaderText="DLRName" DataField="DEALERNAME">
  14.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  15.                                                     <ItemStyle HorizontalAlign="left" Width="250px" />
  16.                                                 </asp:BoundField>
  17.                                                 <asp:BoundField HeaderText="PC CODE" DataField="PCcode">
  18.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  19.                                                     <ItemStyle HorizontalAlign="Left" Width="80px" />
  20.                                                 </asp:BoundField>
  21.                                                 <asp:BoundField HeaderText="NAME" DataField="Name">
  22.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  23.                                                     <ItemStyle HorizontalAlign="Left" Width="200px" />
  24.                                                 </asp:BoundField>
  25.                                                 <asp:BoundField HeaderText="CLASS" DataField="ClassName">
  26.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  27.                                                     <ItemStyle HorizontalAlign="Left" Width="150px" />
  28.                                                 </asp:BoundField>
  29.                                                 <asp:BoundField HeaderText="PROD" DataField="ProdCate_DESC">
  30.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  31.                                                     <ItemStyle HorizontalAlign="Left" Width="100px" />
  32.                                                 </asp:BoundField>
  33.                                                 <asp:BoundField HeaderText="% Ach" DataField="Ach" DataFormatString="{0:N2}">
  34.                                                     <HeaderStyle HorizontalAlign="Center" Wrap="False" />
  35.                                                     <ItemStyle HorizontalAlign="left" Width="80px" />
  36.                                                 </asp:BoundField>
  37.                                             </Columns>
  38.                                         </asp:GridView>
Code Behind
Expand|Select|Wrap|Line Numbers
  1. Partial Class BackEnd_IncCalulationScore
  2.     Inherits System.Web.UI.Page
  3.     Dim DA As New DatabaseServices.DALServices()
  4.  
  5.     Public Property TemplateListSession() As List(Of TemplateField)
  6.         Get
  7.             Return Session("TemplateListSession")
  8.         End Get
  9.         Set(ByVal value As List(Of TemplateField))
  10.             Session("TemplateListSession") = value
  11.         End Set
  12.     End Property
  13.  
  14.  
  15.     Public Property PCCodeTempolary() As String
  16.         Get
  17.             Return ViewState("PCCodeTempolary")
  18.         End Get
  19.         Set(ByVal value As String)
  20.             ViewState("PCCodeTempolary") = value
  21.         End Set
  22.     End Property
  23.  
  24.     Public Property YearTempolary() As String
  25.         Get
  26.             Return ViewState("YearTempolary")
  27.         End Get
  28.         Set(ByVal value As String)
  29.             ViewState("YearTempolary") = value
  30.         End Set
  31.     End Property
  32.  
  33.     Public Property MonthTempolary() As String
  34.         Get
  35.             Return ViewState("MonthTempolary")
  36.         End Get
  37.         Set(ByVal value As String)
  38.             ViewState("MonthTempolary") = value
  39.         End Set
  40.     End Property
  41.  
  42.     Public Property AchTempolary() As Double
  43.         Get
  44.             Return ViewState("AchTempolary")
  45.         End Get
  46.         Set(ByVal value As Double)
  47.             ViewState("AchTempolary") = value
  48.         End Set
  49.     End Property
  50.  
  51.     Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit        
  52.         If Not Me.IsPostBack Then
  53.             PCCodeTempolary = Request.QueryString("PCCode").ToString()
  54.             YearTempolary = Request.QueryString("Year").ToString()
  55.             MonthTempolary = Request.QueryString("Month").ToString()
  56.             AchTempolary = CDbl(Request.QueryString("Ach").ToString())
  57.  
  58.             Dim dv = GetIncentiveScoreColumn()
  59.             If (Not dv.Table Is Nothing) Then 'Check is have data
  60.                 'If dv.Table.Rows.Count > 1 Then 'Add width when column more than 5 column
  61.                 '    Dim width = CInt(grdInCenScore.Width.Value + (dv.Table.Rows.Count * 80))
  62.                 '    grdInCenScore.Width = width
  63.                 'End If
  64.  
  65.                 'Generate manual column
  66.                 TemplateListSession = New List(Of TemplateField)
  67.                 For index = 0 To dv.Table.Rows.Count - 1
  68.                     Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
  69.                     Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
  70.  
  71.                     If CInt(score) > 0 Then
  72.                         TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString()))
  73.                         TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
  74.                     Else
  75.                         TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
  76.                     End If
  77.                 Next
  78.                 TemplateListSession.Add(CreateDtColumn("txtPercenInc"))
  79.             End If
  80.         End If
  81.  
  82.         'If Not grdInCenScore Is Nothing Then
  83.  
  84.         '    If grdInCenScore.Rows.Count > 0 Then
  85.         '        Dim scoreCols = GetIncentiveScoreColumn()
  86.         '        For index = 0 To scoreCols.Table.Rows.Count
  87.         '            Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
  88.         '            Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
  89.         '        Next
  90.         '    End If
  91.         'End If
  92.     End Sub
  93.  
  94.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  95.         Try
  96.             If Not Me.IsPostBack Then
  97.                 PCCodeTempolary = Request.QueryString("PCCode").ToString()
  98.                 YearTempolary = Request.QueryString("Year").ToString()
  99.                 MonthTempolary = Request.QueryString("Month").ToString()
  100.                 AchTempolary = CDbl(Request.QueryString("Ach").ToString())
  101.  
  102.                 RenderGridView()
  103.             End If
  104.         Catch ex As Exception
  105.             ShowAlertMsg(ex, "Page_Load")
  106.         End Try
  107.     End Sub
  108.  
  109.     Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
  110.         'RenderGridView()
  111.         Dim result = InsertIncentiveScore() 'Insert Incentive to DB
  112.         If result Then ' Save success
  113.             ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('บันทึกข้อมูลเรียบร้อยแล้ว');", True)
  114.         Else ' Save fail
  115.             ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('เกิดข้อผิดพลาดไม่สามารถบันทึกข้อมูลได้');", True)
  116.         End If
  117.         'RenderGridView()
  118.         'Response.Redirect(Request.RawUrl)
  119.     End Sub
  120.  
  121.     Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
  122.  
  123.     End Sub
  124.  
  125.     Private Function InsertIncentiveScore() As Boolean 'Insert data
  126.         Try
  127.             DA.BeginTransaction()
  128.             Dim scoreCols = GetIncentiveScoreColumn()
  129.             For index = 0 To scoreCols.Table.Rows.Count
  130.                 Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
  131.                 'Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
  132.                 Dim _scoreDesc = DirectCast(grdInCenScore.FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) '<---- Can not get value from textBoxControl
  133.                 Dim _scoreDescPercen = DirectCast(grdInCenScore.FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9) + "%"), TextBox) 'Score Description percen
  134.  
  135.                 Dim _pcCode = grdInCenScore.Rows(0).Cells(1).Text
  136.                 Dim _year = YearTempolary
  137.                 Dim _month = MonthTempolary
  138.                 Dim _percenAch = grdInCenScore.Rows(0).Cells(6).Text
  139.                 Dim _scoreDetailId = CInt(_scoreDescId)
  140.                 Dim _incScore = IIf(_scoreDesc Is Nothing, "0", _scoreDesc.Text)
  141.                 Dim _IncScorePercen = IIf(_scoreDescPercen Is Nothing, "0", _scoreDescPercen.Text)
  142.                 Dim _postBy = Nzs(Session("Username"))
  143.  
  144.                 DA.ExecuteNonQuery(DA.Transaction, CommandType.StoredProcedure, "spIncentive_CalculationScore_InsertData",
  145.                     DA.CreateParameter("@PCCode", _pcCode, SqlDbType.VarChar),
  146.                     DA.CreateParameter("@Years", _year, SqlDbType.VarChar),
  147.                     DA.CreateParameter("@Months", _month, SqlDbType.VarChar),
  148.                     DA.CreateParameter("@PercentAch", _percenAch, SqlDbType.Float),
  149.                     DA.CreateParameter("@ScoreDetailId", _scoreDetailId, SqlDbType.Int),
  150.                     DA.CreateParameter("@IncScore", CDbl(_incScore), SqlDbType.Float),
  151.                     DA.CreateParameter("@IncScorePercent", CDbl(_IncScorePercen), SqlDbType.Float),
  152.                     DA.CreateParameter("@PostBy", _postBy, SqlDbType.VarChar))
  153.  
  154.             Next
  155.             DA.CommitTransaction()
  156.             Return True
  157.         Catch ex As Exception
  158.             DA.RollBackTransaction()
  159.             ShowAlertMsg(ex, "InsertIncentiveScore")
  160.             Return False
  161.         End Try
  162.     End Function
  163.  
  164.     Private Sub CreateColumnGrdiView(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) ' Render Header-Details GridView
  165.         Try
  166.             Dim _headerGridRow1 As GridViewRow
  167.             Dim _headerGridRow2 As GridViewRow
  168.             Dim dv = GetIncentiveScoreColumn()
  169.  
  170.             'Create header manual column 
  171.             If Not dv.Table Is Nothing Then
  172.                 If e.Row.RowType = DataControlRowType.Header Then
  173.                     _headerGridRow1 = New GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal)
  174.                     _headerGridRow1.CssClass = "DataGridHeader"
  175.                     _headerGridRow1.Width = 160
  176.                     _headerGridRow2 = New GridViewRow(1, -1, DataControlRowType.Header, DataControlRowState.Normal)
  177.                     _headerGridRow2.CssClass = "DataGridHeader"
  178.                     _headerGridRow2.Width = 80
  179.  
  180.                     CreateColumn(_headerGridRow1, "No.", 1, 2)
  181.                     CreateColumn(_headerGridRow1, "DLR Name", 1, 2)
  182.                     CreateColumn(_headerGridRow1, "PC Code", 1, 2)
  183.                     CreateColumn(_headerGridRow1, "Name", 1, 2)
  184.                     CreateColumn(_headerGridRow1, "Class", 1, 2)
  185.                     CreateColumn(_headerGridRow1, "Prod", 1, 2)
  186.                     CreateColumn(_headerGridRow1, "% Ach", 1, 2)
  187.  
  188.                     For index = 0 To dv.Table.Rows.Count - 1
  189.                         Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
  190.                         Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
  191.                         Dim scoreTopic = dv.Table.Rows(index).ItemArray(6) 'Score Topic
  192.                         Dim scorePer = CInt(dv.Table.Rows(index).ItemArray(8)) 'Score Percen
  193.  
  194.                         If CInt(score) > 0 Then
  195.                             CreateColumn(_headerGridRow1, scoreTopic.ToString() + " (" + scorePer.ToString() + "%)", 2, 1)
  196.                             CreateColumn(_headerGridRow2, scoreDesc.ToString(), 1, 1)
  197.                             CreateColumn(_headerGridRow2, scoreDesc.ToString() + "%", 1, 1)
  198.                         Else
  199.                             CreateColumn(_headerGridRow1, scoreTopic.ToString() + " (" + scorePer.ToString() + "%)", 1, 1)
  200.                             CreateColumn(_headerGridRow2, scoreTopic.ToString() + "%", 1, 1)
  201.                         End If
  202.                     Next
  203.                     CreateColumn(_headerGridRow1, "% Inc", 1, 2)
  204.  
  205.                     Dim Grid As GridView = TryCast(sender, GridView)
  206.                     If Grid.Rows.Count <= 0 Then 'Check row count
  207.                         'Input row header to gridview
  208.                         Grid.Controls(0).Controls.AddAt(0, _headerGridRow1)
  209.                         Grid.Controls(0).Controls.AddAt(1, _headerGridRow2)
  210.                     End If
  211.                 End If
  212.             End If
  213.         Catch ex As Exception
  214.             ShowAlertMsg(ex, "RenderHeaderGrdiView")
  215.         End Try
  216.     End Sub
  217.  
  218.     Private Function CreateDtColumn(ByVal name As String) As TemplateField 'Create column
  219.         Dim tmpField = New TemplateField()
  220.         tmpField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
  221.         tmpField.HeaderStyle.Wrap = False
  222.         tmpField.ItemStyle.HorizontalAlign = HorizontalAlign.Left
  223.         tmpField.ItemStyle.Width = 80
  224.  
  225.         Dim txt As TextBox = New TextBox()
  226.         txt.ID = name
  227.         txt.Width = 80
  228.         txt.MaxLength = 20
  229.         txt.Attributes.Add("OnKeyPress", "javascript:chkInputNumeric(this);")
  230.         txt.Text = String.Empty
  231.         txt.ValidationGroup = "Save"
  232.         txt.EnableViewState = True
  233.  
  234.         Dim rfv = New RequiredFieldValidator()
  235.         rfv.ID = "rfv" + name
  236.         rfv.ErrorMessage = "*"
  237.         rfv.ForeColor = Drawing.Color.Red
  238.         rfv.ControlToValidate = txt.ID
  239.         rfv.ValidationGroup = "Save"
  240.  
  241.         Dim txtColumn = New TextColumn
  242.         txtColumn.SetTextColumn(txt, rfv)
  243.         tmpField.ItemTemplate = txtColumn
  244.         'grid.Columns.Add(tmpField)
  245.         Return tmpField
  246.     End Function
  247.  
  248.     Private Sub ShowAlertMsg(ByVal ex As Exception, ByVal remark As String) ' Show alert message when have error
  249.         fnStd.ErrException(ex, remark)
  250.         ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('เกิดความผิดพลาดไม่สามารถทำรายการได้');", True)
  251.     End Sub
  252.  
  253.     Private Function GetIncentiveScoreColumn() As DataView ' Get Incebtive Score column from DB
  254.         Dim dv = New DataView()
  255.         Dim ds = New DataSet()
  256.  
  257.         ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetData",
  258.                                 DA.CreateParameter("@Year", YearTempolary, SqlDbType.VarChar),
  259.                                 DA.CreateParameter("@Month", MonthTempolary, SqlDbType.VarChar))
  260.  
  261.         If ds.Tables(0).Rows.Count > 0 Then
  262.             dv.Table = ds.Tables(0)
  263.         End If
  264.  
  265.         Return dv
  266.     End Function
  267.  
  268.     Private Function GetIncentiveScoreDesc() As DataView ' Get Incebtive Score description from DB
  269.         Dim dv = New DataView()
  270.         Dim ds = New DataSet()
  271.  
  272.         ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetScoreDesc",
  273.                                 DA.CreateParameter("@PCCode", PCCodeTempolary, SqlDbType.VarChar),
  274.                                 DA.CreateParameter("@Ach", AchTempolary, SqlDbType.Money))
  275.  
  276.         If ds.Tables(0).Rows.Count > 0 Then
  277.             dv.Table = ds.Tables(0)
  278.         End If
  279.  
  280.         Return dv
  281.     End Function
  282.  
  283.     Private Function GetIncentiveScorForEdit() As DataView ' Get incentive default value when edit
  284.         Dim ds = New DataSet
  285.         Dim dv = New DataView
  286.         ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetScoreDetail",
  287.                                 DA.CreateParameter("@PCCode", PCCodeTempolary, SqlDbType.VarChar))
  288.  
  289.         If ds.Tables(0).Rows.Count > 0 Then
  290.             dv.Table = ds.Tables(0)
  291.         End If
  292.         Return dv
  293.     End Function
  294.  
  295.     Private Sub RenderGridView() ' Render Gridview
  296.         Dim dv = GetIncentiveScoreColumn()
  297.         grdInCenScore.AutoGenerateColumns = False
  298.  
  299.         Dim incentiveScore = GetIncentiveScorForEdit() 'Check data edit
  300.         If Not incentiveScore.Table Is Nothing Then
  301.  
  302.         Else
  303.             grdInCenScore.DataSource = GetIncentiveScoreDesc()
  304.         End If
  305.  
  306.         If (Not dv.Table Is Nothing) Then 'Check is have data
  307.             If dv.Table.Rows.Count > 1 Then 'Add width when column more than 5 column
  308.                 Dim width = CInt(grdInCenScore.Width.Value + (dv.Table.Rows.Count * 80))
  309.                 grdInCenScore.Width = width
  310.             End If
  311.  
  312.             'Generate manual column
  313.             For Each t In TemplateListSession
  314.                 grdInCenScore.Columns.Add(t)
  315.             Next
  316.             'For index = 0 To dv.Table.Rows.Count - 1
  317.             '    Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
  318.             '    Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
  319.  
  320.             '    If CInt(score) > 0 Then
  321.             '        grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString()))
  322.             '        grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
  323.             '    Else
  324.             '        grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
  325.             '    End If
  326.             'Next
  327.             'CreateDtColumn("txtPercenInc")
  328.         End If
  329.         grdInCenScore.DataBind()
  330.  
  331.     End Sub
  332.  
  333.     Protected Sub grdInCenScore_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdInCenScore.RowCreated
  334.         CreateColumnGrdiView(sender, e)
  335.     End Sub
  336.  
  337.     Protected Sub grdInCenScore_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdInCenScore.Init
  338.         'If Not grdInCenScore Is Nothing Then
  339.  
  340.         '    If grdInCenScore.Rows.Count > 0 Then
  341.         '        Dim scoreCols = GetIncentiveScoreColumn()
  342.         '        For index = 0 To scoreCols.Table.Rows.Count
  343.         '            Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
  344.         '            Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
  345.         '        Next
  346.         '    End If
  347.         'End If
  348.     End Sub
  349. End Class
  350.  
  351. Public Class TextColumn
  352.     Implements ITemplate 'For generate column
  353.  
  354.     Private txtBox As TextBox
  355.     Private validator As RequiredFieldValidator
  356.  
  357.     Public Sub SetTextColumn(ByVal txt As TextBox, ByVal rfv As RequiredFieldValidator) 'Set template details
  358.         txtBox = txt
  359.         validator = rfv
  360.     End Sub
  361.  
  362.     Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
  363.         container.Controls.Add(txtBox)
  364.         container.Controls.Add(validator)
  365.     End Sub
  366. End Class
  367.  
Please help me for this problem
Apr 12 '12 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.