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 InsertIncentive Score() Function or text underline
Client code
Code Behind
Please help me for this problem
Please look and focus this syntax "<----" at InsertIncentive Score() Function or text underline
Client code
Code:
<asp:GridView ID="grdInCenScore" runat="server" AutoGenerateColumns="False" BCellPadding="2"
Width="1024px" AllowPaging="True" EmptyDataText="No Data" ShowHeaderWhenEmpty="True"
CssClass="DataGrid" ShowHeader="False">
<RowStyle CssClass="DataGridItem" Height="28px" />
<PagerStyle HorizontalAlign="Left" CssClass="pager" />
<HeaderStyle CssClass="DataGridHeader" />
<AlternatingRowStyle CssClass="DataGridAlternating" />
<Columns>
<asp:BoundField HeaderText="No" DataField="No">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Center" Width="30px" />
</asp:BoundField>
<asp:BoundField HeaderText="DLRName" DataField="DEALERNAME">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="left" Width="250px" />
</asp:BoundField>
<asp:BoundField HeaderText="PC CODE" DataField="PCcode">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Width="80px" />
</asp:BoundField>
<asp:BoundField HeaderText="NAME" DataField="Name">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Width="200px" />
</asp:BoundField>
<asp:BoundField HeaderText="CLASS" DataField="ClassName">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="PROD" DataField="ProdCate_DESC">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="Left" Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="% Ach" DataField="Ach" DataFormatString="{0:N2}">
<HeaderStyle HorizontalAlign="Center" Wrap="False" />
<ItemStyle HorizontalAlign="left" Width="80px" />
</asp:BoundField>
</Columns>
</asp:GridView>
Code:
Partial Class BackEnd_IncCalulationScore
Inherits System.Web.UI.Page
Dim DA As New DatabaseServices.DALServices()
Public Property TemplateListSession() As List(Of TemplateField)
Get
Return Session("TemplateListSession")
End Get
Set(ByVal value As List(Of TemplateField))
Session("TemplateListSession") = value
End Set
End Property
Public Property PCCodeTempolary() As String
Get
Return ViewState("PCCodeTempolary")
End Get
Set(ByVal value As String)
ViewState("PCCodeTempolary") = value
End Set
End Property
Public Property YearTempolary() As String
Get
Return ViewState("YearTempolary")
End Get
Set(ByVal value As String)
ViewState("YearTempolary") = value
End Set
End Property
Public Property MonthTempolary() As String
Get
Return ViewState("MonthTempolary")
End Get
Set(ByVal value As String)
ViewState("MonthTempolary") = value
End Set
End Property
Public Property AchTempolary() As Double
Get
Return ViewState("AchTempolary")
End Get
Set(ByVal value As Double)
ViewState("AchTempolary") = value
End Set
End Property
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
If Not Me.IsPostBack Then
PCCodeTempolary = Request.QueryString("PCCode").ToString()
YearTempolary = Request.QueryString("Year").ToString()
MonthTempolary = Request.QueryString("Month").ToString()
AchTempolary = CDbl(Request.QueryString("Ach").ToString())
Dim dv = GetIncentiveScoreColumn()
If (Not dv.Table Is Nothing) Then 'Check is have data
'If dv.Table.Rows.Count > 1 Then 'Add width when column more than 5 column
' Dim width = CInt(grdInCenScore.Width.Value + (dv.Table.Rows.Count * 80))
' grdInCenScore.Width = width
'End If
'Generate manual column
TemplateListSession = New List(Of TemplateField)
For index = 0 To dv.Table.Rows.Count - 1
Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
If CInt(score) > 0 Then
TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString()))
TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
Else
TemplateListSession.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
End If
Next
TemplateListSession.Add(CreateDtColumn("txtPercenInc"))
End If
End If
'If Not grdInCenScore Is Nothing Then
' If grdInCenScore.Rows.Count > 0 Then
' Dim scoreCols = GetIncentiveScoreColumn()
' For index = 0 To scoreCols.Table.Rows.Count
' Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
' Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
' Next
' End If
'End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not Me.IsPostBack Then
PCCodeTempolary = Request.QueryString("PCCode").ToString()
YearTempolary = Request.QueryString("Year").ToString()
MonthTempolary = Request.QueryString("Month").ToString()
AchTempolary = CDbl(Request.QueryString("Ach").ToString())
RenderGridView()
End If
Catch ex As Exception
ShowAlertMsg(ex, "Page_Load")
End Try
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'RenderGridView()
Dim result = InsertIncentiveScore() 'Insert Incentive to DB
If result Then ' Save success
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('บันทึกข้อมูลเรียบร้อยแล้ว');", True)
Else ' Save fail
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('เกิดข้อผิดพลาดไม่สามารถบันทึกข้อมูลได้');", True)
End If
'RenderGridView()
'Response.Redirect(Request.RawUrl)
End Sub
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
End Sub
Private Function InsertIncentiveScore() As Boolean 'Insert data
Try
DA.BeginTransaction()
Dim scoreCols = GetIncentiveScoreColumn()
For index = 0 To scoreCols.Table.Rows.Count
Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
'Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
[U] Dim _scoreDesc = DirectCast(grdInCenScore.FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) '<---- Can not get value [/U]from textBoxControl
Dim _scoreDescPercen = DirectCast(grdInCenScore.FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9) + "%"), TextBox) 'Score Description percen
Dim _pcCode = grdInCenScore.Rows(0).Cells(1).Text
Dim _year = YearTempolary
Dim _month = MonthTempolary
Dim _percenAch = grdInCenScore.Rows(0).Cells(6).Text
Dim _scoreDetailId = CInt(_scoreDescId)
Dim _incScore = IIf(_scoreDesc Is Nothing, "0", _scoreDesc.Text)
Dim _IncScorePercen = IIf(_scoreDescPercen Is Nothing, "0", _scoreDescPercen.Text)
Dim _postBy = Nzs(Session("Username"))
DA.ExecuteNonQuery(DA.Transaction, CommandType.StoredProcedure, "spIncentive_CalculationScore_InsertData",
DA.CreateParameter("@PCCode", _pcCode, SqlDbType.VarChar),
DA.CreateParameter("@Years", _year, SqlDbType.VarChar),
DA.CreateParameter("@Months", _month, SqlDbType.VarChar),
DA.CreateParameter("@PercentAch", _percenAch, SqlDbType.Float),
DA.CreateParameter("@ScoreDetailId", _scoreDetailId, SqlDbType.Int),
DA.CreateParameter("@IncScore", CDbl(_incScore), SqlDbType.Float),
DA.CreateParameter("@IncScorePercent", CDbl(_IncScorePercen), SqlDbType.Float),
DA.CreateParameter("@PostBy", _postBy, SqlDbType.VarChar))
Next
DA.CommitTransaction()
Return True
Catch ex As Exception
DA.RollBackTransaction()
ShowAlertMsg(ex, "InsertIncentiveScore")
Return False
End Try
End Function
Private Sub CreateColumnGrdiView(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) ' Render Header-Details GridView
Try
Dim _headerGridRow1 As GridViewRow
Dim _headerGridRow2 As GridViewRow
Dim dv = GetIncentiveScoreColumn()
'Create header manual column
If Not dv.Table Is Nothing Then
If e.Row.RowType = DataControlRowType.Header Then
_headerGridRow1 = New GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal)
_headerGridRow1.CssClass = "DataGridHeader"
_headerGridRow1.Width = 160
_headerGridRow2 = New GridViewRow(1, -1, DataControlRowType.Header, DataControlRowState.Normal)
_headerGridRow2.CssClass = "DataGridHeader"
_headerGridRow2.Width = 80
CreateColumn(_headerGridRow1, "No.", 1, 2)
CreateColumn(_headerGridRow1, "DLR Name", 1, 2)
CreateColumn(_headerGridRow1, "PC Code", 1, 2)
CreateColumn(_headerGridRow1, "Name", 1, 2)
CreateColumn(_headerGridRow1, "Class", 1, 2)
CreateColumn(_headerGridRow1, "Prod", 1, 2)
CreateColumn(_headerGridRow1, "% Ach", 1, 2)
For index = 0 To dv.Table.Rows.Count - 1
Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
Dim scoreTopic = dv.Table.Rows(index).ItemArray(6) 'Score Topic
Dim scorePer = CInt(dv.Table.Rows(index).ItemArray(8)) 'Score Percen
If CInt(score) > 0 Then
CreateColumn(_headerGridRow1, scoreTopic.ToString() + " (" + scorePer.ToString() + "%)", 2, 1)
CreateColumn(_headerGridRow2, scoreDesc.ToString(), 1, 1)
CreateColumn(_headerGridRow2, scoreDesc.ToString() + "%", 1, 1)
Else
CreateColumn(_headerGridRow1, scoreTopic.ToString() + " (" + scorePer.ToString() + "%)", 1, 1)
CreateColumn(_headerGridRow2, scoreTopic.ToString() + "%", 1, 1)
End If
Next
CreateColumn(_headerGridRow1, "% Inc", 1, 2)
Dim Grid As GridView = TryCast(sender, GridView)
If Grid.Rows.Count <= 0 Then 'Check row count
'Input row header to gridview
Grid.Controls(0).Controls.AddAt(0, _headerGridRow1)
Grid.Controls(0).Controls.AddAt(1, _headerGridRow2)
End If
End If
End If
Catch ex As Exception
ShowAlertMsg(ex, "RenderHeaderGrdiView")
End Try
End Sub
Private Function CreateDtColumn(ByVal name As String) As TemplateField 'Create column
Dim tmpField = New TemplateField()
tmpField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
tmpField.HeaderStyle.Wrap = False
tmpField.ItemStyle.HorizontalAlign = HorizontalAlign.Left
tmpField.ItemStyle.Width = 80
Dim txt As TextBox = New TextBox()
txt.ID = name
txt.Width = 80
txt.MaxLength = 20
txt.Attributes.Add("OnKeyPress", "JavaScript:chkInputNumeric(this);")
txt.Text = String.Empty
txt.ValidationGroup = "Save"
txt.EnableViewState = True
Dim rfv = New RequiredFieldValidator()
rfv.ID = "rfv" + name
rfv.ErrorMessage = "*"
rfv.ForeColor = Drawing.Color.Red
rfv.ControlToValidate = txt.ID
rfv.ValidationGroup = "Save"
Dim txtColumn = New TextColumn
txtColumn.SetTextColumn(txt, rfv)
tmpField.ItemTemplate = txtColumn
'grid.Columns.Add(tmpField)
Return tmpField
End Function
Private Sub ShowAlertMsg(ByVal ex As Exception, ByVal remark As String) ' Show alert message when have error
fnStd.ErrException(ex, remark)
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "clientScript", "alert('เกิดความผิดพลาดไม่สามารถทำรายการได้');", True)
End Sub
Private Function GetIncentiveScoreColumn() As DataView ' Get Incebtive Score column from DB
Dim dv = New DataView()
Dim ds = New DataSet()
ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetData",
DA.CreateParameter("@Year", YearTempolary, SqlDbType.VarChar),
DA.CreateParameter("@Month", MonthTempolary, SqlDbType.VarChar))
If ds.Tables(0).Rows.Count > 0 Then
dv.Table = ds.Tables(0)
End If
Return dv
End Function
Private Function GetIncentiveScoreDesc() As DataView ' Get Incebtive Score description from DB
Dim dv = New DataView()
Dim ds = New DataSet()
ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetScoreDesc",
DA.CreateParameter("@PCCode", PCCodeTempolary, SqlDbType.VarChar),
DA.CreateParameter("@Ach", AchTempolary, SqlDbType.Money))
If ds.Tables(0).Rows.Count > 0 Then
dv.Table = ds.Tables(0)
End If
Return dv
End Function
Private Function GetIncentiveScorForEdit() As DataView ' Get incentive default value when edit
Dim ds = New DataSet
Dim dv = New DataView
ds = DA.ExecuteDataset(CommandType.StoredProcedure, "spIncentive_CalculationScore_GetScoreDetail",
DA.CreateParameter("@PCCode", PCCodeTempolary, SqlDbType.VarChar))
If ds.Tables(0).Rows.Count > 0 Then
dv.Table = ds.Tables(0)
End If
Return dv
End Function
Private Sub RenderGridView() ' Render Gridview
Dim dv = GetIncentiveScoreColumn()
grdInCenScore.AutoGenerateColumns = False
Dim incentiveScore = GetIncentiveScorForEdit() 'Check data edit
If Not incentiveScore.Table Is Nothing Then
Else
grdInCenScore.DataSource = GetIncentiveScoreDesc()
End If
If (Not dv.Table Is Nothing) Then 'Check is have data
If dv.Table.Rows.Count > 1 Then 'Add width when column more than 5 column
Dim width = CInt(grdInCenScore.Width.Value + (dv.Table.Rows.Count * 80))
grdInCenScore.Width = width
End If
'Generate manual column
For Each t In TemplateListSession
grdInCenScore.Columns.Add(t)
Next
'For index = 0 To dv.Table.Rows.Count - 1
' Dim score = dv.Table.Rows(index).ItemArray(7) 'Score
' Dim scoreDesc = dv.Table.Rows(index).ItemArray(9) 'Score Description
' If CInt(score) > 0 Then
' grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString()))
' grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
' Else
' grdInCenScore.Columns.Add(CreateDtColumn("txt" + scoreDesc.ToString() + "%"))
' End If
'Next
'CreateDtColumn("txtPercenInc")
End If
grdInCenScore.DataBind()
End Sub
Protected Sub grdInCenScore_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdInCenScore.RowCreated
CreateColumnGrdiView(sender, e)
End Sub
Protected Sub grdInCenScore_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdInCenScore.Init
'If Not grdInCenScore Is Nothing Then
' If grdInCenScore.Rows.Count > 0 Then
' Dim scoreCols = GetIncentiveScoreColumn()
' For index = 0 To scoreCols.Table.Rows.Count
' Dim _scoreDescId = scoreCols.Table.Rows(index).ItemArray(5) 'Score Description Id
' Dim xx = DirectCast(grdInCenScore.Rows(0).Cells(index + 7).FindControl("txt" + scoreCols.Table.Rows(index).ItemArray(9)), TextBox) 'Score Description
' Next
' End If
'End If
End Sub
End Class
Public Class TextColumn
Implements ITemplate 'For generate column
Private txtBox As TextBox
Private validator As RequiredFieldValidator
Public Sub SetTextColumn(ByVal txt As TextBox, ByVal rfv As RequiredFieldValidator) 'Set template details
txtBox = txt
validator = rfv
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
container.Controls.Add(txtBox)
container.Controls.Add(validator)
End Sub
End Class