ASP.NET Gridview - sql

I formed the table shown below picture 1 with GridView but there is a something which I want and I explain that picture 2 (İ didn't use GridView there).
When the data come from database to column of Durum, if it is Aktif, it shows Aktif Button or if it is Pasif, it shows Pasif Button.
How can do this?

You can do pretty much whatever you want assuming you don't use default column binding but rather you define your own.
<asp:GridView ... AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
this is where your template can do
pretty much anything including conditionals
<asp:Button runat="server"
ForeColor="<%# Bind("column")=="value" ? "Red" ? "Blue" %> />
Note that dynamic binding can be applied to any property. You could have two different buttons then and dynamically bind their Visible property so that they are visible or hidden depending on a value of one of dataset columns.
More on dynamic templates in multiple tutorials, e.g.
https://msdn.microsoft.com/en-us/library/bb288032.aspx

Add this TemplateField Code in your GridView:
<asp:TemplateField HeaderText="Durum">
<ItemTemplate>
// Bind your durum column from database in Eval
<asp:Label ID="lblDurum" Visible="false" runat="server" Text='<% #Eval("durum") %>'></asp:Label>
<asp:Button ID="btnAktif" Visible="false" runat="server" Text="Aktif" />
<asp:Button ID="btnPasif" Visible="false" runat="server" Text="Pasif" />
</ItemTemplate>
</asp:TemplateField>
Code Behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button Aktif = e.Row.FindControl("btnAktif") as Button;
Button Pasif = e.Row.FindControl("btnPasif") as Button;
string Durum = ((Label)e.Row.FindControl("lblDurum")).Text;
if (Durum=="Aktif")
Aktif.Visible = true;
else
Pasif.Visible = true;
}
}
Note: Don't forget to add OnRowDataBound in GrindView <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >

Related

Changing a columns contents in a GridView from VB code

I am displaying a grid of data which includes a users name and profile pic etc.
If they haven’t uploaded a profile picture I have set the code below to set imgPic.ImageUrl = "~/files/images/blankProfilePic.png"
However, this works only for the 1st page of 6 pages of data displayed.. As soon as you switch to the 2nd page I get the missing picture icon as the code below is only working for the initial page displayed.
I need to change this code to work on every page as it is only called when the page loads.
VB CODE
Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
Dim acc As New accounts(Membership.GetUser.ProviderUserKey)
If acc.region = "North East" Then
For Each r As GridViewRow in gdvNorthEast.Rows
If r.RowType = DataControlRowType.DataRow Then
Dim imgPic As Image
imgPic = r.Cells(4).FindControl("imgProfilePic")
If imgPic.ImageUrl = "~/catalog/images/"
imgPic.ImageUrl = "~/files/images/blankProfilePic.png"
End If
End If
Next r
End If
ASP.NET
<asp:SqlDataSource
ID="DSLeaderboardNorthEast"
runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT tblAccounts.contactName, tblAccounts.profilePic, tblAccounts.minAge, tblAccounts.maxAge, tblAccounts.AccountID, tblAccounts.region
FROM tblAccounts
WHERE tblAccounts.region='North East'
ORDER BY tblAccounts.contactName ">
</asp:SqlDataSource>
<asp:GridView ID="gdvNorthEast" width="100%" runat="server" AllowPaging="True" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="accountID" DataSourceID="DSLeaderboardNorthEast" PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Image ID="imgProfilePic" AlternateText="Players profile picture" runat="server" width="100px" height="100px" ImageUrl='<%# "~/catalog/images/" & Eval("ProfilePic").ToString %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="contactName" HeaderText="Player Name" />
<asp:BoundField DataField="minAge" HeaderText="Won" />
<asp:BoundField DataField="maxAge" HeaderText="Lost" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HyperLink ID="hypMessage" runat="server" CssClass="nyroModalMsg" NavigateUrl='<%# "~/sendLeaderboardMessage.aspx?" & "&aID=" & Eval("accountID").ToString %>'>Msg</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Your foreach loop for assigning default image should be reusable method.
Use PageIndexChanged event handler to call the same reusable method.
Update:
Since the above option is not helping, follow this post
//RowDataBound Event
protected void gdvNorthEast_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking the RowType of the Row
if(e.Row.RowType==DataControlRowType.DataRow)
{
//your logic goes here without foreach loop
}
}
Use the Gridview_RowDataBound event to make the function of substitution instead use a for instruction

Textboxes inside gridview validation

I have a gridview in which I have 100 rows of Textboxes. All textboxes have same id 'TxtEmpcode'. User enters data in some rows of gridview. How do I validate textboxes such that one Employee code is entered only once in textboxes. This is to avoid duplicate entry of data. Suppose a user enters Employee code '1234', this should not allowed in other rows of textboxes. If they enter, a message should appear as 'Employee Code has already been entered'.
Can anyone tell how to achieve this?
<asp:GridView ID="GridView2" runat="server" style="margin-left: 23px; margin-top: 11px;" Width="420px" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333" GridLines="None" Height="213px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Employee Code">
<ItemTemplate>
<asp:TextBox ID="TxtEmpcode" runat="server" OnTextChanged="TxtId_TextChanged" AutoPostBack ="true" ></asp:TextBox>
</ItemTemplate>
You can use logic of it as per your requirement.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<script>
function IsValidTest(Control) {
name = Control.name;
var list = document.getElementById("TxtEmpcode");
var contents = $("[id=TxtEmpcode]");
var TextboxId = name;
var Txtbox = document.getElementsByName(name);
var TextboxValue = Txtbox[0].value;
for (i = 0; i < contents.length; i++)
{
var currenttextboxName=contents[i].name;
var currenttextboxValue=contents[i].value;
//Compare currently changed value with existing values in other textboxes
if (name != currenttextboxName && currenttextboxValue == TextboxValue)
{
alert('Employee Code has already been entered');
Txtbox[0].value = '';
return false;
}
}
return true;
}
</script>
<div>
<asp:GridView ID="GridView2" runat="server" Style="margin-left: 23px; margin-top: 11px;"
Width="420px" CellPadding="4" AutoGenerateColumns="False" ForeColor="#333333"
GridLines="None" Height="213px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Employee Code">
<ItemTemplate>
<asp:TextBox ID="TxtEmpcode" runat="server" AutoPostBack="true" ClientIDMode="Static" onchange="javascript: return IsValidTest(this);"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>

Update TimeRecorded on edititemtemplate label vb.net

I'm trying to have a label in the edititemtemplate of my gridview show the current date and time when the user clicks the edit linkbutton. When I put date.now in the data binding box, I can see the result I want, but when I click update, I get an error that the field can't be null. It works fine when I try it for the footer row, but not the edit row. Here's the footer row code that works:
'Get Time Recorded
Dim lblFtrTimeRecorded As Label = GridView1.FooterRow.FindControl("lblFtrTimeRecorded")
lblFtrTimeRecorded.Text = Date.Now
Here's the template field .aspx code:
<asp:TemplateField HeaderText="TimeRecorded" SortExpression="TimeRecorded">
<EditItemTemplate>
<asp:Label ID="lblEditTimeRecorded" runat="server"
Text='<%# Bind("TimeRecorded") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFtrTimeRecorded" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblTimeRecorded" runat="server"
Text='<%# Bind("TimeRecorded") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Any help is greatly appreciated!
Write this code :
Dim lblFtrTimeRecorded As Label = GridView1.Rows[GridView1.EditIndex].FindControl("lblFtrTimeRecorded")
lblFtrTimeRecorded.Text = Date.Now

Sending email to all the email adresses in gridview which are checked

I have a grid view control in my application.
Please see the below code.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="CPUserID" DataSourceID="GetSelectDelegatesDataSource">
<Columns>
<asp:BoundField HeaderStyle-CssClass="gridview_header" HeaderStyle-ForeColor="White" Visible="false" DataField="EmailAddress" HeaderText="Email Address" SortExpression="EmailAddress">
<HeaderStyle CssClass="gridview_header" ForeColor="White"></HeaderStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<input id="masterCheck" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
<HeaderStyle CssClass="gridview_header" ForeColor="White"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
And I have a image button
<asp:ImageButton ID="ibtnSendInvites" Visible="false" runat="server" ImageUrl="~/images1/send_button.png" />
If you see above code you can find that there is check box functionality in my gridview. I have email address boundfield in my gridview. I want to send an email to the email addresses which are been checked in gridview.
Please provide the vb.net code for the same
Very quickly thrown together, you can get the jist.. I didn't test it or anything.
Dim emailList As New List(Of String)
For Each curRow As GridViewRow In GridView1.Rows
Dim chkSelect As CheckBox = CType(curRow.Cells(1).FindControl("chkSelect"), CheckBox)
If chkSelect.Checked Then
emailList.Add(curRow.Cells(0).Text)
End If
Next
' you now have a generic list of email addresses..
System.Web.Mail provide the functionality to send mail from .Net framework. Download the sample project Send Mail- codeproject and see how this is implemented.
Check this link on BulkEditGridView. It's just like a GridView, but you can edit (or perform actions on) multiple rows of a gridview with one click. I use it and love it.

How to remove one item from string in a textbox

I have a gridview with 2 columns.
First field contains checkbox named chkSelect and second column is a label which is binded with EmailId.
<asp:GridView ID="gvwNewsLetter" runat="server" AutoGenerateColumns="false" DataKeyNames="UserID">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelectMail" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmailID">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("EmailID")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
When I check each checkbox I have to display mailid in corresponding row in a textarea which is outside gridview like" abc#gmail.com,sdf#gmail.com". If I uncheck inbetween I have to remove that particular id from textbox. Can anybody help give the code to remove mailid on unchecking the checkbox.
Can you not just rebuild the entire string each time a checkbox is checked/unchecked? Might be faster than trying to parse through and modify the existing string each time.