can't add DataKeyNames into Grid View - asp.net

I'm originally having problems with detecting the status of a checkbox in my grid View.
Apparently one of the solutions to the problem would be adding DataKeyNames value to the Grid View. But if i add DataKey value to my Grid View it's not being populated when I run the code.
Can anybody point me on my mistake?
here is the original head of the grid View which can be populated:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="1500px">
Here is the code after i add the DataKeyNames:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="1500px" DataKeyNames="account_id">
And here is the backend code to populate the gridView
Dim StrQwery As String = "SELECT account_id, account_name bla bla bla"
Dim smd As MySqlCommand
smd = New MySqlCommand(StrQwery, myconn)
smd.CommandType = CommandType.Text
Dim da As New MySqlDataAdapter(smd)
Dim cb As New MySqlCommandBuilder(da)
Dim ds As New DataSet()
da.Fill(ds)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
I can't understand why the values are not filled in Grid View after I add DatakeyNames
the entire code of Grid View
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="1500px" >
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" textAlign="right"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>

Related

Gridview, dynamic data within asp.net not working?

When I use the code below, my gridview (ID=Gridview2) object will populate perfectly using the datasource that is hard coded. I'd like to use a dynamically generated datatable (which when debugging the datatable is populated successfully complete with rows and columns). When I try to bind the dynamic data to my other gridview object (ID=Gridview1) and I verify that it has the datasource as my newly created datatable, nothing appears on the screen?
What am I doing wrong? Do I need to define templates for the dynamic code to work?
<asp:GridView ID="GridView2" runat="server" AllowSorting="True" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="true"
EmptyDataText="No results found" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
AllowSorting="True" AutoGenerateColumns="True">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
Code-behind:
protected void btnSearch_Click(object sender, EventArgs e)
{
string domainToQueryFor = "domain";
string pinToQueryFor = "account";
DBConnectionlib.DBClass dbReader = new DBConnectionlib.DBClass();
dbReader.connectionInformation = #"Server=tcp:XXXXXXXXX,1433 ;Database=" + databaseName + ";Trusted_Connection=false;UID=" + databaseUserName + ";Pwd=" + databasePassword + "; ApplicationIntent=ReadWrite;Timeout=60;MultiSubnetFailover=True";
dbReader.tableName = tableName;
string currentSqlQuery = "select * from " + dbReader.tableName + " WHERE domain like '" + domainToQueryFor + "' and pin like '" + pinToQueryFor + "'";
dbReader.queryStatement = currentSqlQuery;
List<string> results = dbReader.readFromSqlDatabaseReturnList();
DataTable dt = createDataTable(results);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I had to add this to get it to portray dynamically
foreach (System.Data.DataColumn item in dt.Columns)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = item.ColumnName;
nameColumn.HeaderText = item.ColumnName;
GridView1.Columns.Add(nameColumn);
}
Basically without the column names explicitly stated/added, the gridview will not display. They could probably also be hard coded in the html code with a <%bind%> command, but I wanted it more dynamic so I did it the above way.

VB.NET checkbox problems

Web site in Visual Studio 2010 with VB. I created a GridView with a checkbox column, but my code behind is not recognizing the checked rows. Runs through with no error but never sees a checked row.
<asp:GridView
ID="gvwOrderDetails"
DataKeyNames="ID"
runat="server"
BackColor="White"
BorderColor="#DEDFDE"
BorderStyle="None"
BorderWidth="1px"
CellPadding="4"
ForeColor="Black"
GridLines="Vertical">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="OrderSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Protected Sub btnVoid_Click(sender As Object, e As System.EventArgs) Handles btnVoid.Click
Dim atLeastOneRowVoided As Boolean = False
For Each row As GridViewRow In gvwOrderDetails.Rows
Dim cb As CheckBox = TryCast(row.Cells(0).FindControl("OrderSelector"), CheckBox)
If cb IsNot Nothing AndAlso cb.Checked Then
atLeastOneRowVoided = True
Dim orderID As Integer = _
Convert.ToInt32(gvwOrderDetails.DataKeys(row.RowIndex).Value)
lbl1.Text &= String.Format( _
"This would have voided ProductID {0}<br />", orderID)
End If
Next
End Sub

How to update gridview through design code/ aspx page code

I'm trying to update GridView every time I update, delete or insert any record. Now I have provided sql data source code for GridView in Design Code not form code. Now how can I update it from there ? When I write GridView1.databind() on form code, it says
> Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Can someone tell me how to DataBind in design view, to update GridView every time I insert/update/delete record ?
Here is GridView1 Code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" Width="284px">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="surname" HeaderText="surname" SortExpression="surname" />
<asp:BoundField DataField="amount" HeaderText="amount" SortExpression="amount" />
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myDbConnectionString %>" SelectCommand="SELECT [name], [surname], [amount] FROM [Table1]"></asp:SqlDataSource>
Set the DataSourceID to null.
GridView1.DataSourceID = null;
GridView1.DataSource = dt;
GridView1.DataBind();
That error was coming because data was being binded on both Design view code as well as web form backend code.
I simply added GridView1.DataSourceID = null;
and that did the job.

Formatting datetime object

I have a dateTime field that i am showing in GridView. The problem is I just need to Show The date of the system And not the time but it shows both date and time. What appropriate formatting should be applied?
this sets the date in textbox:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBoxdate.Text = DateTime.Today.ToShortDateString();
}
}
Retrieves from table:
public static List<Workassign> GetTable()
{
List<Workassign> listValues = new List<Workassign>();
string connectionString = "server=(local);database=project_zeshan;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from Assign_Work", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Workassign ob = new Workassign();
ob.listItem_1 =rdr["listitem_1"].ToString() ;
ob.listItem_2 = rdr["listitem_2"].ToString();
ob.Description = rdr["Description"].ToString();
ob.Date= DateTime.Parse(rdr["Date"].ToString());
ob.Image = rdr["Image"].ToString();
listValues.Add(ob);
}
return listValues;
}
And the gridView.aspx code:
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="listitem_1" HeaderText="ListItem1" />
<asp:BoundField DataField="listItem_2" HeaderText="listItem2" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height= "50px" Width = "100px" ImageUrl='<%# Bind("Image") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</div>
</form>
Try this:
<asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:MM/dd/yyyy}" />
You can format the DateTime however you like using ToString() with format string created from the choices here: MSDN - Custom Date and Time Format Strings
// For a standard U.S.-style date:
myDateTime.ToString("MM/dd/yyyy")
// For ISO-style:
myDateTime.ToString("yyyy-MM-dd")
And so on.
EDIT
#JohnH correctly pointed out that in the specific context of working with a GridView, you wouldn't use ToString or other methods, but rather provide a DataFormatString attribute. I'll leave my answer for general use cases of formatting a date and the link to the MSDN resource containing the available format strings.

fixing width of a gridview in asp.net

I want to fix width of gridview. I am filling gridview as following;
sorgu = "select urun.urunId as \"İş No\",urun.modelNo as \"Model No\",modelAd as \"Model Adı\",bedenAd as \"Beden\", adet as \"Adet\""
+ ",aciklama as \"Açıklama\", kesmeTalimat as \"Kesim Talimatı\", atolyeTalimat as \"Atölye Talimatı\", yikamaTalimat as \"Yıkama Talimatı\", utuTalimat as \"Ütü Talimatı\", (k4.ad+' '+k4.soyad) as \"Kesim\", (k1.ad+' '+k1.soyad) as \"Atölye\""
+ ",(k2.ad+' '+k2.soyad) as \"Yıkama\",(k3.ad+' '+k3.soyad) as \"Ütü\", (k5.ad+' '+k5.soyad) as \"Kontrol\" from kullanici k1,kullanici k4,kullanici k5,kullanici k2,kullanici k3,model,beden,urun,fason,isTalimat,durum"
+ " where urun.urunId= fason.urunId and urun.urunId=isTalimat.urunId and urun.urunId=durum.urunId and model.modelNo=urun.modelNo and beden.bedenNo=urun.bedenNo and"
+ " fason.atolye=k1.id and fason.yikama=k2.id and fason.kesimci=k4.id and fason.kontrol=k5.id and fason.utu=k3.id";
connection.Open();
command.Connection = connection;
command.CommandText = sorgu;
dr = command.ExecuteReader();
DataTable dtTumISler = new DataTable();
dtTumISler.Load(dr);
dgvTumIsler.DataSource = dtTumISler;
dgvTumIsler.DataBind();
dr.Close();
connection.Close();
dtTumISler.Dispose();
Here dgvTumİsler is my gridview. I have tried the following code to make fixed length. But it does not work;
for (int i = 0; i < dgvTumIsler.Columns.Count; i++)
{
dgvTumIsler.Columns[i].ItemStyle.Width = 100;
}
Here dgvTumİsler.Columns.Count value is 1. So it does not work. Is there a way to solve this problem or is there another way to make a gridview fixed width.
HTML code:
<asp:GridView ID="dgvTumIsler" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" OnSelectedIndexChanged="dgvTumIsler_SelectedIndexChanged">
<Columns>
<asp:CommandField ButtonType="Button" SelectText="Seç" ShowCancelButton="False" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
Here is an example how you can do it.Give it a try
<asp:GridView ID="GridView1" AutoGenerateEditButton="True" runat="server" AutoGenerateColumns="False" width="600px">
<Columns>
<asp:BoundField HeaderText="UserId"
DataField="UserId"
SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
</Columns>
</asp:GridView>
You can use the CssClass attribute to set a css class and use that to set the width
<RowStyle CssClass="myRow">
...
<asp:CommandField ButtonType="Button" SelectText="Seç" CssClass="mybutton"/>
...
<style>
.myRow td{width: 100px;}
.mybutton{width: 100px}
</style>

Resources