Click here to Skip to main content
11,435,048 members (49,199 online)
Rate this: bad
good
Please Sign up or sign in to vote.
I have a page with gridview in it.my gridview shows the products Information and Admin can Edit gridviews columns.two of my columns show the brand name and category name for each product;I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop) in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop. brands name in my brand table in database are:Samsung
 
Nokia,Sony Ericsson,Apple,LG,HTC....
 
and my categories name in category table are :
 
Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g,wt18i,w8,500,n8...
 
when I click the Edit button,first item in the branddrop is Equal to brandlable.Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.text in ItemTemplate and the category drop does not show the related categories name to brandname.for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work. I dont know how to solve it.I'll become so thankfull if anybody help me
 
this is my first code:
 
          <asp:TemplateField HeaderText="brand name">
            <ItemTemplate>
                <asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
                <asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%>
 
                <asp:DropDownList  ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true"  OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
            </EditItemTemplate>
         </asp:TemplateField>
 
        <asp:TemplateField HeaderText="category name">
            <ItemTemplate>
                <asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
            </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
               <asp:DropDownList ID="categoryDrop" runat="server"  AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3">   <%-- --%>
               </asp:DropDownList>
               <asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
              <asp:SqlDataSource ID="SqlDataSource3" runat="server"   ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=@idfrombrands " >
                <SelectParameters>
                  <asp:ControlParameter ControlID="brandDrop"
                    Name="idfrombrands" PropertyName="SelectedValue" Type="Int32"  />
                </SelectParameters>
               </asp:SqlDataSource>
 
           </EditItemTemplate>
        </asp:TemplateField>



this is my code behind for
GridView1_RowDataBound and GridView1_RowUpdating:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int brand=0;
int category=0;
//Drop Brand--------------------------------------

DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");

if (list1.SelectedItem.Value != null)
{
brand = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand

}
else
{
brand = Convert.ToInt32(lbl.Text);

}
//Drop Category----------------------------------------

DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");

//int NewIdFromBrand2 = -1;
if (list2.SelectedItem.Value != null)
{
category = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2

}
else
{
category = Convert.ToInt32(lbl2.Text);
}

//Photo-------------------------------------------

string photoname = System.Guid.NewGuid().ToString();

GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage");
if (fileUpload != null && fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);

SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
}
else
{
SqlDataSource1.UpdateParameters["path"].DefaultValue = l bl3.Text;//oldImage.Text;
}
int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
DataTable tb = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateProduct";
cmd.Parameters.AddWithValue("@brandid", brand );
cmd.Parameters.AddWithValue("@catid", category );
cmd.Parameters.AddWithValue("@pid", prid);
try
{
cn.Open();
cmd.ExecuteNonQuery();
SqlDataSource1.DataBind();

}
catch (Exception ex2)
{


}
finally { cn.Close(); }
//GridView1.EditIndex = -1;
//GridView1.DataBind();

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
//Label1.Text = ddlStatus.SelectedValue;

}
}

}

}
}
Posted 3-Jan-13 1:50am
elmirag635
Comments
Rai Pawan at 3-Jan-13 7:01am
   
Please use proper formatting to state you question. Your question seems to be enclosed in the code tags and part of your code seems to be out of the code tags. - Pawan
aspnet_regiis -i at 3-Jan-13 7:16am
   
And the problem is?
elmirag at 3-Jan-13 9:50am
   
categorydrop works fine when I select an Item from branddrop.my problem is ,it does not work well untill I select an item from branddrop .when I select an item from branddrop ,the categorydrop shows related categories name and its ok but when I click edit button before I select any item from branddrop because I still do not select any item from brand drop categorydrop does not work well .I dont know how to solve it
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

I changed my event like this and it works fine now:


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();

SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
}
}

}

}
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

[
ورود به سامانه ]




[به مدیریت سامانه خوش آمدید]

[<<
] [:کاربر محترم]
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

-------------------- view desing Girid -----------




bgcolor="#9999FF">



<div style="text-align: right">

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" width="100%" xmlns:asp="#unknown">
ShowFooter="True" BackColor="#CCCCCC" BorderColor="#999999" BorderWidth="3px"
CellPadding="4" CellSpacing="2" DataKeyNames="code" Style="color: #FFC080" ForeColor="Black"
OnRowCommand="doDelete">


<selectedrowstyle backcolor="#6699FF" font-bold="True" forecolor="White" />

ForeColor="White" Height="10px" HorizontalAlign="Center" VerticalAlign="Middle"
Wrap="True" />
<headerstyle backcolor="Black" forecolor="White" cssclass="text" font-bold="True">
Wrap="True" />


<%--شماره--%>
<asp:templatefield headertext="کد تدریس">

<asp:literal id="lit" runat="server">


<asp:literal id="lit_number" runat="server" text="<%# eval("code") %>">



<%--شماره--%>
<%--نام--%>
<asp:templatefield headertext="کد تدریس">

<asp:textbox id="edit_name" runat="server" text="<%# Bind("tadrisName") %>" height="20px">
Width="88px">


<asp:textbox id="txt_name" runat="server" width="86px" height="20px">


<%#Eval("tadrisName")%>



<%--نام--%>

<%-- دكمه هاي انصراف وویرایش --%>
<asp:commandfield buttontype="Button" canceltext="انصراف" edittext="ویرایش" showeditbutton="True">
UpdateText="ویرایش" HeaderText="ویرایش">

BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" />


<%-- حذف --%>
<asp:templatefield headertext="حذف" showheader="False" itemstyle-forecolor="#DEDFDE">

<asp:button id="btnRemove" runat="server" causesvalidation="False" commandname="Delete">
Text="حذف" OnClientClick="return confirm('?آیا مایل به حذف این پست هستید');" />


Font-Names="Tahoma" Font-Size="X-Small" ForeColor="Black" />


<asp:templatefield headertext="حذف انتخابي" itemstyle-forecolor="#DEDFDE">

<asp:button commandname="Delete1" text="حذف" id="btnRemove1" runat="server" borderstyle="Solid">
OnClientClick="return confirmDelete();" BorderWidth="1px" BackColor="#DEDFDE"
Font-Names="Tahoma" Font-Size="11px" CssClass="menu" />


<asp:checkbox id="ChkRemove" runat="server">


<headerstyle backcolor="Black" horizontalalign="Center" />

ForeColor="Red" />


<%--<asp:buttonfield buttontype="Button" commandname="btnselect" text="انتخاب" headertext="دکمه انتخاب " />--%>

</headerstyle>









--------------------------- source code asp.vb.net -----------------

--------------------------- source code asp.vb.net -----------------


--------------------------- source code asp.vb.net -----------------


Imports System.Web.Security
Imports System.Web.UI
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Imports System.Diagnostics
Imports System.IO
Imports System.Drawing
Imports System.Security.Cryptography



Partial Class TarifEtelaatForm

Inherits System.Web.UI.Page

Public name_tadris As String

Dim objConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("objConnect").ConnectionString)
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("objConnect").ConnectionString)
Dim conS As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("objConnect").ConnectionString)


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



'If User.IsInRole("modir") = False Then
' Response.Redirect("DeFault.aspx")
' FormsAuthentication.SignOut()
'End If

If Not (User.Identity.IsAuthenticated) Then
'alert("You clicked me!");
'Response.Write("<script>کاربر محترم شما باید قبلا ثبت نام کنید!'></script>")
Response.Redirect("DeFault.aspx")
Exit Sub
End If


'بررسی برای سطح دسترسی
'============================================================
Dim bank As LevelvorodDataContext = New LevelvorodDataContext
Dim Query = From T In bank.Table_Levels
Where (T.codeper = User.Identity.Name) _
Select T
Try
If Query.Count > 0 Then
For Each record In Query
If record.codeLevel > 1 Then
Response.Redirect("DeFault.aspx")
FormsAuthentication.SignOut()
End If
Next
End If
Catch ex As Exception
Finally
If (Not bank Is Nothing) Then bank.Connection.Close()
End Try
'=========================================================


If (User.Identity.IsAuthenticated) = True Then


Call MAxTadrisCode()

If Not IsPostBack Then
BindGridView()
BindGridViewSelect()
End If


End If

End Sub

Private Sub MAxTadrisCode()

Dim objMaxId As New SqlCommand
objConnection.Open()
objMaxId.Connection = objConnection
objMaxId.CommandText = "Select Max(code) From Table_tadrisName"
Dim MaxId As Object = objMaxId.ExecuteScalar()
If MaxId Is DBNull.Value Then
MaxId = 0
End If
TextBoxCode.Text = MaxId + 1
objMaxId.Cancel()
objConnection.Close()

End Sub


Private Sub dgBind()

Dim DS As New DataSet()
Dim objDataAdapter As New SqlDataAdapter( _
"Select code,tadrisName From Table_TadrisName Order By code Desc", objConnection)
objConnection.Open()
objDataAdapter.Fill(DS, "Table_TadrisName")
GridView1.DataSource = DS.Tables("Table_TadrisName")
GridView1.DataBind()
objConnection.Close()

End Sub


Private Sub MAxpostCode()

'بدست آوردن بزرگترین کد رکورداز جدول
Dim objMaxId As New SqlCommand
objConnection.Open()
objMaxId.Connection = objConnection
objMaxId.CommandText = "Select Max(code) From Table_TadrisName"
Dim MaxId As Object = objMaxId.ExecuteScalar()
If MaxId Is DBNull.Value Then
MaxId = 0
End If
TextBoxcode.Text = MaxId + 1
objMaxId.Cancel()
objConnection.Close()
'MaxId

End Sub


Public Sub BindGridView()
Dim Dta As SqlDataAdapter = Nothing
Dim Ds As DataSet
Dim com As New SqlCommand("select * from Table_TadrisName", con)
Try
Dta = New SqlDataAdapter(com)
Ds = New DataSet
Dta.Fill(Ds, "tadrisName")
GridView1.DataSource = Ds
GridView1.DataBind()
Finally
If (Not com Is Nothing) Then com.Dispose()
If (Not Dta Is Nothing) Then Dta.Dispose()
End Try
End Sub

Public Sub BindGridViewSelect()

Dim DtaS As SqlDataAdapter = Nothing
Dim DsS As DataSet
Dim comS As New SqlCommand("select * from Table_TadrisName ", conS)
Try
DtaS = New SqlDataAdapter(comS)
DsS = New DataSet
DtaS.Fill(DsS, "tadrisName")
GridView1.DataSource = DsS
GridView1.DataBind()
Finally
If (Not comS Is Nothing) Then comS.Dispose()
If (Not DtaS Is Nothing) Then DtaS.Dispose()
End Try

End Sub

Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

Try

If e.CommandName = "sabt" Then
Dim str_name As String
'Dim str_family As String
'Dim str_city As String

Dim rowFooter As GridViewRow = GridView1.FooterRow

str_name = CType(rowFooter.FindControl("txt_name"), TextBox).Text


Dim bank1 As DataClassesTadrisDataContext = New DataClassesTadrisDataContext
Dim Query = From T In bank1.Table_tadrisNames
Where (T.tadrisName = str_name) _
Select T
If Query.Count > 0 Then
Lblpm.Text = "این نام دوره تدریس قبلاایجاد شده است، خطا "
TextBoxTadrisName.Text = ""
Call MAxTadrisCode()
Else


Dim com As New SqlCommand
com.Connection = con
com.CommandText = "insert into Table_TadrisName values(@tadrisName)"
com.Parameters.AddWithValue("@tadrisName", str_name)
'com.Parameters.AddWithValue("@code", str_family)
'com.Parameters.AddWithValue("@tel", phon)

Try

con.Open()
com.ExecuteNonQuery()

Catch ex As SqlException
MsgBox("اطلاعات ورودی شما ناقص میباشد. خواهشمندیم کاملش کنید", MsgBoxStyle.DefaultButton1, "خطا")

Response.Write(ex.Message.ToString())
Finally
If con.State <> ConnectionState.Closed Then con.Close()
If (Not com Is Nothing) Then com.Dispose()
GridView1.EditIndex = -1
BindGridView()
End Try

End If

End If

Catch ex As Exception
Response.Write(ex.Message.ToString)
End Try

'selected Girid حالت انتخاب رديفي از گريد
If e.CommandName = "btnselect" Then

Try

Dim idx As Integer
idx = Convert.ToInt32(e.CommandArgument)
For i = 0 To 5
GridView1.Rows(idx).Cells(i).BackColor = System.Drawing.Color.LightSkyBlue
Next
GridView1.RowStyle.BorderColor = Color.Blue
'بدست اوردن شماره مربوط به رديف انتخاب شده'
Dim rowid As GridViewRow = GridView1.Rows(idx)
Dim int_number As Integer = CType(rowid.FindControl("lit_number"), Literal).Text
'''''''''''''''''''''''''''''''''''''''''''''''

'جستجو براي فيلدهاي ركورد انتخابي'
Dim My_DS As New DataSet
Dim cmdText As String = "SELECT * FROM Table_tadrsName where code =" & int_number & ""
Using sqlAdapter As New SqlDataAdapter(cmdText, ConfigurationManager.ConnectionStrings("objConnect").ConnectionString)
sqlAdapter.Fill(My_DS)
End Using
ReadDataTable_1(My_DS.Tables(0))

Catch ex As SqlException
Response.Redirect("Default.aspx")
Response.Write(ex.Message.ToString())
Finally
If conS.State <> ConnectionState.Closed Then conS.Close()
'If (Not comS Is Nothing) Then comS.Dispose()
BindGridView()
BindGridViewSelect()
End Try
End If


End Sub

Private Sub ReadDataTable_1(ByVal dtInput As DataTable)
' روال دستيابي به محتويات جدول با مورد خواسته شده
Dim sumResult As Long = 0
For Each row As DataRow In dtInput.Rows
TextBoxCode.Text = row("code").ToString
TextBoxTadrisName.Text = row("tadrsName").ToString
Response.Write("
موفق باشید")
'Response.Redirect("PostMashaghel.aspx")
Next

End Sub

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim rowEdit As GridViewRow = GridView1.Rows(e.RowIndex)
Dim com As New SqlCommand
GridView1.ShowFooter = True
GridView1.EditIndex = -1

Dim int_number As String = CType(rowEdit.FindControl("lit_number"), Literal).Text
'Dim str_aks As String = String.Empty
'con.Open()
'com.Connection = con
'com.CommandText = "select * from Table_tadrisName where code ='" & int_number & "'"
'Dim reader As SqlDataReader = com.ExecuteReader
'If reader.HasRows = True Then
' reader.Read()
' str_aks = (reader.GetString(1))
'End If
'con.Close()

Try
Dim edit_name As String
'Dim edit_family As String

edit_name = CType(rowEdit.FindControl("edit_name"), TextBox).Text

'Table_tadrisNames :جستجو از جدول
Dim bank1 As DataClassesTadrisDataContext = New DataClassesTadrisDataContext
Dim Query = From T In bank1.Table_tadrisNames
Where (T.tadrisName = edit_name) _
Select T
If Query.Count > 0 Then
Lblpm.Text = "این نام دوره تدریس قبلاایجاد شده است، خطا "
TextBoxTadrisName.Text = ""
Call MAxTadrisCode()
Else

'edit_family = CType(rowEdit.FindControl("edit_family"), TextBox).Text
'edit_city = CType(rowEdit.FindControl("edit_list"), DropDownList).SelectedItem.Text

com.Connection = con
com.CommandText = "update Table_tadrisName set tadrisName=@tadrisName where code= '" & int_number & "'"
com.Parameters.AddWithValue("tadrisName", edit_name)
'com.Parameters.AddWithValue("family", edit_family)
'com.Parameters.AddWithValue("tel", phon)

Try

con.Open()
com.ExecuteNonQuery()
Lblpm.Text = ""
Catch ex As SqlException
Response.Write(ex.Message.ToString())
Finally
If con.State <> ConnectionState.Closed Then con.Close()
If (Not com Is Nothing) Then com.Dispose()
GridView1.EditIndex = -1
BindGridView()
End Try

End If

Catch ex As Exception
Response.Write(ex.Message.ToString)
End Try

End Sub

Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated

'If e.Row.RowType = DataControlRowType.Footer Then

If e.Row.RowType = ListItemType.Footer Then

Dim btnAdd As New Button
btnAdd.ID = "btnAdd"
btnAdd.Text = "اضافه"
btnAdd.CommandName = "sabt"
btnAdd.BorderStyle = BorderStyle.Solid
btnAdd.BorderWidth = New Unit(1, UnitType.Pixel)
btnAdd.BackColor = Color.FromArgb(Int32.Parse("6666FF", Globalization.NumberStyles.AllowHexSpecifier))
btnAdd.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px")
e.Row.Cells(3).Controls.Add(btnAdd)


'بدست آوردن آخرین شماره رکورد از بانک
Dim lit As Literal = e.Row.FindControl("lit")
con.Open()
Dim com As New SqlCommand
com.Connection = con
com.CommandText = "SELECT MAX(code) FROM Table_tadrisName"
Dim a1 As Object = com.ExecuteScalar, p As Integer
If a1.ToString <> "" Then
p = CType(a1, Integer) + 1
lit.Text = p
con.Close()
Else
p = 1
lit.Text = p
con.Close()
End If
'--------------------------------------------------------------

End If



If ((e.Row.RowType = DataControlRowType.DataRow) And (e.Row.RowState = DataControlRowState.Edit)) Or ((e.Row.RowType = DataControlRowType.DataRow) And (e.Row.RowState.ToString() = "Alternate, Edit")) Then

Dim cancelButton As Button = CType(e.Row.Cells(2).Controls(2), Button)
cancelButton.BackColor = Color.FromKnownColor(KnownColor.LightBlue)
cancelButton.BorderWidth = Unit.Pixel(1)
cancelButton.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px")

Dim updateButton As Button = CType(e.Row.Cells(2).Controls(0), Button)
updateButton.BackColor = Color.FromKnownColor(KnownColor.Green)
updateButton.BorderWidth = Unit.Pixel(1)
updateButton.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px")

End If


'If ((e.Row.RowType = DataControlRowType.DataRow) And (e.Row.RowState = DataControlRowState.Edit)) Or ((e.Row.RowType = DataControlRowType.DataRow)) Then

' ' دررديف اول گريد حذف انجام نشود= دكمه حذف كار نكند
' Dim delete As New Button
' delete = CType(e.Row.Cells(3).FindControl("btnRemove"), Button)
' If 0 = GridView1.Rows.Count Then
' delete.Enabled = False
' Else
' delete.Enabled = True
' End If

' ' از كار انداختن تيك چك باكس كه انجام نشود= چك باكس آن رديف كار نكند
' Dim ChkRemove As New CheckBox
' ChkRemove = CType(e.Row.Cells(4).FindControl("ChkRemove"), CheckBox)
' If 0 = GridView1.Rows.Count Then
' ChkRemove.Enabled = False
' Else
' ChkRemove.Enabled = True
' End If

'End If


' ====================================================================
' +... ايجاد دكمه حذف براي انتخابهاي چك باكسي
Dim btnRemove1 As New Button
btnRemove1.ID = "btnRemove1"
btnRemove1.Text = "حذف"
btnRemove1.CommandName = "Delete1"
btnRemove1.BorderStyle = BorderStyle.Solid
btnRemove1.BorderWidth = New Unit(1, UnitType.Pixel)
btnRemove1.Attributes.Add("Style", "Font-Family:Tahoma; Font-Size:11px")
'e.Row.Cells(3).Controls.Add(btnRemove1)
' + ...
' =====================================================================


End Sub

'ايجاد روالي چهت حذف در صورت تيك دارشدن چك باكسها ...
Sub doDelete(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)

'=+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
If (e.CommandName = "Delete1") Then

Dim chkRemove As WebControls.CheckBox
Dim strIDs As String = ""
Dim boolCheck As Boolean = False

For Each gvRow As GridViewRow In GridView1.Rows
chkRemove = DirectCast(gvRow.FindControl("ChkRemove"), WebControls.CheckBox)
If chkRemove.Checked Then
boolCheck = True
strIDs += GridView1.DataKeys(gvRow.RowIndex).Value & ","
End If
Next

If boolCheck = True Then
Dim strSQL As String = "Delete from Table_tadrisName where code IN (" & strIDs.Substring(0, strIDs.LastIndexOf(",")) & ")"
Dim strConnection As String = System.Configuration.ConfigurationManager.ConnectionStrings("objConnect").ConnectionString
Dim Cnn As New SqlConnection(strConnection)
Dim Cmd As New SqlCommand(strSQL, Cnn)

Try
Cnn.Open()
Cmd.ExecuteNonQuery()
Lblpm.Text = ""
Catch ex As SqlException
Response.Write(ex.Message.ToString())
Finally
If (Cmd IsNot Nothing) Then Cmd.Dispose()
If (Cnn.State <> ConnectionState.Closed) Then Cnn.Close()
BindGridView()
'BindGridView(IIf(ViewState("drpPagingIndex") IsNot Nothing, Convert.ToInt32(ViewState("drpPagingIndex")), 0), 5)
End Try
End If

End If
'=+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
End Sub

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

'Dim Da As SqlDataAdapter
'Dim Ds As New DataSet
'Dim com As SqlCommand


'Dim edit_list As New DropDownList
'edit_list = CType(e.Row.Cells(4).FindControl("edit_list"), DropDownList)
'If ((e.Row.RowType = DataControlRowType.DataRow) And (e.Row.RowState = DataControlRowState.Edit)) Or ((e.Row.RowType = DataControlRowType.DataRow) And (e.Row.RowState.ToString() = "Alternate, Edit")) Then
' com = New SqlCommand("select * from shahr", con)
' Da = New SqlDataAdapter(com)
' Ds = New DataSet
' Da.Fill(Ds, "shahr")
' edit_list.DataSource = Ds.Tables(0).DefaultView
' edit_list.DataValueField = "city"
' edit_list.DataBind()

' edit_list.SelectedValue = Session("list")

'End If

'Dim dd_list As DropDownList
'dd_list = CType(e.Row.Cells(4).FindControl("list_shahr"), DropDownList)
'If e.Row.RowType = ListItemType.Footer Then
' com = New SqlCommand("select * from shahr", con)
' Da = New SqlDataAdapter(com)
' Ds = New DataSet
' Da.Fill(Ds, "shahr")
' dd_list.DataSource = Ds.Tables(0).DefaultView
' dd_list.DataValueField = "city"
' dd_list.DataBind()
'End If

If e.Row.RowType = DataControlRowType.Pager Then
e.Row.Attributes.Add("onClick", "ClickColor('" + e.Row.ClientID + "')")
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor = 'ff00ff'")
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = 'blue'")
End If

End Sub


Protected Sub GridView1_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
GridView1.ShowFooter = True
GridView1.EditIndex = -1
BindGridView()
Call MAxTadrisCode()
End Sub

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
GridView1.ShowFooter = False
'Dim str_city As String = String.Empty
'str_city = CType(GridView1.Rows(e.NewEditIndex).Cells(5).Controls(0), DataBoundLiteralControl).Text.Trim
'Session("list") = String.Concat(str_city)
GridView1.EditIndex = e.NewEditIndex
BindGridView()
End Sub

Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim rowEdit As GridViewRow = GridView1.Rows(e.RowIndex)
Dim com As New SqlCommand
Dim int_number As String = CType(rowEdit.FindControl("lit_number"), Literal).Text

'Dim str_aks As String = String.Empty
'con.Open()
'com.Connection = con
'com.CommandText = "select * from Table_tadrisName where code ='" & int_number & "'"
'Dim reader As SqlDataReader = com.ExecuteReader
'If reader.HasRows = True Then
' reader.Read()
' str_aks = (reader.GetString(1))
'End If
'con.Close()

com.Connection = con
com.CommandText = "delete from Table_tadrisName where code= '" & int_number & "'"
Try
con.Open()
com.ExecuteNonQuery()

'System.IO.File.Delete(Server.MapPath(str_aks))
Catch ex As SqlException
Response.Write(ex.Message.ToString())
Finally
If con.State <> ConnectionState.Closed Then con.Close()
If (Not com Is Nothing) Then com.Dispose()
BindGridView()
End Try


End Sub

Protected Sub _TarifEtelaatForm_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
For Each gvRow As GridViewRow In GridView1.Rows
Dim ref_Chk As CheckBox = DirectCast(gvRow.FindControl("chkRemove"), CheckBox)
ClientScript.RegisterArrayDeclaration("chk_Array_cods", String.Concat("'", ref_Chk.ClientID, "'"))
Next

'If (GridView1.Rows.Count > 0) Then
' gridelement.Value = GridView1.FooterRow.Cells().Controls(1).ClientID & "," & GridView1.FooterRow.Cells(5).Controls(0).ClientID & "," & GridView1.HeaderRow.Cells(6).Controls(1).Controls(0).Controls(0).ClientID
'End If

End Sub


Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged

'Dim ID As Integer = GridView1.DataKeys(GridView1.SelectedIndex).Value

'Dim cmdText As String = "IF NOT EXISTS( SELECT * FROM Tbl_Girid_Select WHERE (ID=@ID) ) INSERT INTO tbl_Girid_Select SELECT * FROM girid WHERE (ID=@ID)"

'Using objConn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbTestConnectionString").ConnectionString)
' Using objCmd As New SqlCommand(cmdText, objConn)
' objConn.Open()
' objCmd.Parameters.AddWithValue("@ID", ID)
' objCmd.ExecuteNonQuery()
' objConn.Close()
' End Using
'End Using
'GridView1.DataBind()
End Sub




'Protected Sub GridView2_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView2.RowDeleting


' Call MAxTadrisCode()

' 'If MsgBox("آيا مطمئن هستيد كه ميخواهيداين رکور راحذف كنيد" _
' ' , MsgBoxStyle.Question + MsgBoxStyle.YesNo + _
' ' MsgBoxStyle.MsgBoxRight, "موافقت باعمل حذف") = MsgBoxResult.Yes Then
' ' objConnection.Open()
' ' Dim objcommand As New SqlCommand
' ' objcommand.Connection = objConnection
' ' objcommand.CommandText = "Delete Table_TadrisName Where" & _
' ' " code=" & GridView2.Rows(e.RowIndex).Cells(2).Text
' ' objcommand.ExecuteNonQuery()
' ' objConnection.Close()
' ' dgBind()
' 'Else
' ' Exit Sub
' 'End If

' Dim rowEdit As GridViewRow = GridView2.Rows(e.RowIndex)
' Dim com As New SqlCommand
' Dim int_number As String = GridView2.Rows(e.RowIndex).Cells(2).Text
' Dim str_aks As String = String.Empty

' 'objConnection.Open()

' 'com.Connection = objConnection
' 'com.CommandText = "select * from Table_TadrisName where code ='" & int_number & "'"
' 'Dim reader As SqlDataReader = com.ExecuteReader
' 'If reader.HasRows = True Then
' ' reader.Read()
' ' str_aks = (reader.GetString(1))
' 'End If
' 'objConnection.Close()

' com.Connection = objConnection
' com.CommandText = "delete from Table_TadrisName where code ='" & int_number & "'"
' Try
' objConnection.Open()
' com.ExecuteNonQuery()

' 'System.IO.File.Delete(Server.MapPath(str_aks))
' Catch ex As SqlException
' Response.Write(ex.Message.ToString() & "خطا")
' Finally
' If objConnection.State <> ConnectionState.Closed Then objConnection.Close()
' If (Not com Is Nothing) Then com.Dispose()
' 'BindGridView()
' End Try
'End Sub



Protected Sub BtnSabt_Click(sender As Object, e As System.EventArgs) Handles BtnSabt.Click


If TextBoxTadrisName.Text = "" Then

Lblpm.Text = "کاربر محترم نام دوره تدریس باید تکمیل شود،خطا"

Else

'بدست آوردن بزرگترین کد رکورد از جدول
Dim objMaxId As New SqlCommand
objConnection.Open()
objMaxId.Connection = objConnection
objMaxId.CommandText = "Select Max(code) From Table_tadrisName"
Dim MaxId As Object = objMaxId.ExecuteScalar()
If MaxId Is DBNull.Value Then
MaxId = 0
End If
objMaxId.Cancel()
objConnection.Close()
'''''''''''''''''''''

'Table_tadrisNames :جستجو از جدول
Dim bank1 As DataClassesTadrisDataContext = New DataClassesTadrisDataContext
Dim Query = From T In bank1.Table_tadrisNames
Where (T.tadrisName = TextBoxTadrisName.Text) _
Select T
If Query.Count > 0 Then
Lblpm.Text = "این نام دوره تدریس قبلاایجاد شده است، خطا "
TextBoxTadrisName.Text = ""
Call MAxTadrisCode()
Else

Try

Dim bank As DataClassesTadrisDataContext = New DataClassesTadrisDataContext
Dim Table_tadris As New Table_tadrisName

Table_tadris.code = MaxId + 1
Table_tadris.tadrisName = TextBoxTadrisName.Text

bank.Table_tadrisNames.InsertOnSubmit(Table_tadris)
bank.SubmitChanges()

Lblpm.Text = "اطلاعات با موفقیت ثبت شد"


Catch ex As Exception

Lblpm.Text = "کاربر محترم مجددااقدام شود،اطلاعات با موفقیت ثبت نشد،خطا،"

Finally

'Lblpm.Text = ""

End Try

Response.Redirect("TarifEtelaatForm.aspx")
Call MAxTadrisCode()

End If

End If


'Dim objCommand As New SqlCommand
'Dim objMaxId As New SqlCommand

'objConnection.Open()
'objCommand.Connection = objConnection
'objCommand.CommandText = "Insert Into Table_tadrisName(code" & _
' ",tadrisName) Values(@code," & _
' "@tadrisName)"

'objMaxId.Connection = objConnection
'objMaxId.CommandText = "Select Max(code) From Table_tadrisName"
'objMaxId.Clone()


'Dim MaxId As Object = objMaxId.ExecuteScalar()
'If MaxId Is DBNull.Value Then
' MaxId = 0
'End If
'objConnection.Close()

'objCommand.Parameters.AddWithValue("@code", MaxId + 1)
'objCommand.Parameters.AddWithValue("@tadrisName", TextBoxTadrisName.Text)
''objCommand.Parameters.AddWithValue("@postdate", jc.WhatDay)
''objCommand.Parameters.AddWithValue("@posttime", Now.ToShortTimeString)
'objConnection.Open()
'objCommand.ExecuteNonQuery()

'Dim intResult As Integer = objCommand.ExecuteNonQuery()
'If intResult > 0 Then
' Lblpm.Text = "با موفقیت انجام شد"
'Else
' Lblpm.Text = "خطا ! مجددا اقدام شود"
'End If
'objConnection.Close()

'' بازیابی مجدد جدول
'Dim DS As New DataSet()
'objConnection.Open()
'Dim objDataAdapter As New SqlDataAdapter( _
'"Select code,tadrisName From Table_TadrisName Order By code Desc", objConnection)
'objDataAdapter.Fill(DS, "Table_TadrisName")
'GridView2.DataSource = DS.Tables("Table_TadrisName")
'GridView2.DataBind()
'objConnection.Close()

'Dim RowEdit As Integer = Application("RowEdit").ToString
'Dim objCommand As New SqlCommand
'objCommand.Connection = objConnection
'objCommand.CommandText = "Update Table_TadrisName Set code='" & TextBoxCode.Text & "',tadrisName='" & TextBoxTadrisName.Text & "' Where code=" & TextBoxCode.Text
'objConnection.Open()
'objCommand.ExecuteNonQuery()
'objConnection.Close()
'dgBind()
'Response.Redirect("previouspost.aspx")

End Sub

Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
'FormsAuthentication.SignOut()
End Sub

Protected Sub BtnShow_Click(sender As Object, e As System.EventArgs) Handles BtnShow.Click
Response.Redirect("LoginModir.aspx")
'Call MAxTadrisCode()
End Sub


End Class


  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.150428.2 | Last Updated 9 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100