I have a dropdownlist control in a gridview control. The grid view control and the dropdown are connected to a datasource.
On submit, the dropdown control only picks the value of the first index.
Here's the ASPX Code:
<asp:GridView ID="gvQuestions" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="qID" HeaderText="QID" />
<asp:BoundField DataField="Question" HeaderText="Questions" />
<asp:TemplateField HeaderText="Response">
<ItemTemplate>
<asp:DropDownList ID="ddlResponse" runat="server" AppendDataBoundItems="True" AutoPostBack="false"
DataSourceID="ResponseSDS" DataTextField="response" DataValueField="responseID"
CssClass="ddlStyle" OnSelectedIndexChanged="ddlResponse_SelectedIndexChanged">
<%--<asp:ListItem Enabled="True" Selected="false"><--Selected Value--></asp:ListItem>--%>
</asp:DropDownList>
<asp:SqlDataSource ID="ResponseSDS" runat="server" ConnectionString="<%$ ConnectionStrings:HSELeadershipSurveyConnectionString %>"
SelectCommand="SELECT * FROM [tblResponse]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#0085C9" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#0085C9" 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>
And here's the code behind for the button click event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Get the responses for the questions
foreach (GridViewRow masterData in gvQuestions.Rows)
{
qID = int.Parse(masterData.Cells[0].Text);
//qID = (int)gvQuestions.DataKeys[(masterData.RowIndex)].Value;
//response = ((DropDownList)masterData.FindControl("ddlResponse")).SelectedValue.ToString();
DropDownList ddl = (DropDownList)gvQuestions.Rows[qID].FindControl("ddlResponse");
responses = ddl.SelectedValue.ToString();
}
}
The button click event has triggered a postback so the dropdownlist value has been reset to the default first index. Also note that the Page_Load event will happen before your button click event.
The row Index obtained from the qID is incorrect. Values of qId could start from 1 but the row index of the grid view starts from 0.
So when the qID ( row index as per your code) is 1 you think it is accessing the first row but instead it accesses the second row ( with row index as 1) ending up picking the selected value of the drop down in second row
So you are using a wrong value to obtain the row index. If you are not convinced with my answer try testing your code with the below it will give you the selected value of drop down in first row.
DropDownList ddl = (DropDownList)gvQuestions.Rows[0].FindControl("ddlResponse");
responses = ddl.SelectedValue.ToString();
FIX: Use the below code behind for the button click event, hope it helps:
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Get the responses for the questions
foreach (GridViewRow masterData in gvQuestions.Rows)
{
// the actual way to get your row index
int rowIndex = masterData.RowIndex;
//qID = (int)gvQuestions.DataKeys[(masterData.RowIndex)].Value;
//response = ((DropDownList)masterData.FindControl("ddlResponse")).SelectedValue.ToString();
DropDownList ddl = (DropDownList)gvQuestions.Rows[rowIndex ].FindControl("ddlResponse");
responses = ddl.SelectedValue.ToString();
}
}
Related
I want to insert specific row values based on check box click. The design and source is given below. From the design I have to select some Items. If I click approve, I have to store those check box checked row values into DB. Help me to find a proper solution.
Design:
ASPX:
C#:
The given below code is getting the entire gridview value and storing into db. How can I modify this code as per above requirements.
protected void btnApprove_Click(object sender, EventArgs e)
{
ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter rs;
rs = new ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter();
foreach (GridViewRow row in GridView2.Rows)
{
string ItemName = row.Cells[0].Text;
string Quantity = row.Cells[1].Text;
rs.testInsert(ItemName, Quantity);
}
}
You need to iterate through your gridview and find check box by Id in cell of current row.
foreach (GridViewRow row in GridView2.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
bool chk = chkRow.Checked;
// Do your stuff
}
}
Source: http://www.aspsnippets.com/Articles/GridView-with-CheckBox-Get-Selected-Rows-in-ASPNet.aspx
The given below code is working perfectly.
foreach (GridViewRow row in GridView2.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox1") as CheckBox);
if (chkRow.Checked)
{
string ItemName = row.Cells[0].Text;
string Quantity = row.Cells[1].Text;
rs.testInsert(ItemName, Quantity);
}
}
}
Here is my GridView
<asp:GridView
ID="grdAccounts"
class="table table-condensed"
runat="server"
AutoGenerateColumns="False"
CellPadding="4"
ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="CUST_NAME" HeaderText="Name" />
<asp:BoundField DataField="CUST_NUMBER" HeaderText="Account Number" />
<asp:BoundField DataField="BR_CODE" HeaderText="CIF Number" />
<asp:TemplateField HeaderText="Select" >
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" ItemStyle-HorizontalAlign="Right" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="SingleCheckboxCheck(this)" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle CssClass="pagination-ys" />
<RowStyle BackColor="#E3EAEB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
c#(I assumed as the required value is in the 1 cell of the selected row.)
string accnbr = string.Empty;
foreach (GridViewRow gvrow in grdAccounts.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
cif += gvrow.Cells[1].Text + ',';
}
}
I'm trying to create a gridview with an extra column that contains a hyperlink for each row. Unfortunately my hyperlinks doesn't start from the top of the column, instead they are started from the second row of the hyperlink's column.
See this picture for more information >>> http://i.imgur.com/TLsVo5s.png
As you can see in that picture, there is a 'view' column that contains hyperlinks, but the problem is the first row is always empty. The hyperlink that's on the second row should be on the first, and the third should be on the second, and so on.
Can anyone show me where I went wrong?
Here is my gridview declaration on my aspx page:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnSorting="GridView1_Sorting" PageSize="20" DataKeyNames="no_kwitansi"
DataSourceID="home1" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" RowStyle-Wrap="False" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<RowStyle HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
<Columns>
<asp:BoundField HeaderText="#" />
<asp:BoundField DataField="no_kwitansi" HeaderText="No.Kwitansi" SortExpression="no_kwitansi" ReadOnly="True" />
<asp:BoundField DataField="nama_vendor" HeaderText="Vendor" SortExpression="nama_vendor" />
<asp:BoundField DataField="nama_pekerja" HeaderText="Pekerja" SortExpression="nama_pekerja" />
<asp:BoundField DataField="nama_penanggungjawab" HeaderText="Penanggungjawab" SortExpression="nama_penanggungjawab" />
<asp:BoundField DataField="satuan" HeaderText="Satuan" SortExpression="satuan" />
<asp:BoundField DataField="jumlah" HeaderText="Nominal" SortExpression="jumlah" />
<asp:BoundField DataField="tanggal" HeaderText="Tanggal" SortExpression="tanggal" />
</Columns>
</asp:GridView>
Here is my C# code behind:
This is my page_load function, I created the template field here.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["SortExpr"] = Sort_Direction;
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
home1.DataBind();
}
}
Here is my gridview rowDataBound function, where I create the hyperlink.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
hlContro.NavigateUrl = "./Home.aspx?ID=" + GridView1.Rows[i].Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
}
e.Row.Cells[8].Controls.Add(hlContro);
}
}
so why not just a template field, and remove all the server side boilerplate? What happen if you would change position of your column?
Below is the solution where you need not to write anything in your server side code. Simple and easy.
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("no_kwitansi") %>'
NavigateUrl= '<%# "./Home.aspx?ID=" + Eval("no_kwitansi") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.
Just write code like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlContro = new HyperLink();
hlContro.NavigateUrl = "./Home.aspx?ID=" + e.Row.Cells[1].Text;
//hlContro.ImageUrl = "./sample.jpg";
hlContro.Text = "Documents";
//GridView1.Rows[i].Cells[0].Controls.Add(hlContro);
e.Row.Cells[8].Controls.Add(hlContro);
}
}
why are you adding it from code behind even you can add in html page
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="test1" runat="server" ForeColor="#525252" Text="Documents" />
</ItemTemplate>
</asp:TemplateField>
a similar example is shown on this link you can try Link
I have a GridView that has a Like and a Dislike Button in each Row.
What I want to do is for the user to be able to click only one of those per Row and Enable or Disable that Button per row when that particular Button is clicked.
I have a Sql Table tblVote that has a Field with the Name Vote. This Keeps a tally for the user if they have voted for that item. If the user clicks the Dislike Button for the first record it will write a 0 to the Vote Column under itemId 1. If user clicks on Like it will write a 1 and so on for each record. I have this part working already. How can I read from the table and issue that Button that state depending on the value on the Vote Field on tblVote.
Table:
ItemId | UserID | Vote
1 | 123 | 0
2 | 123 | 1
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AutoGenerateColumns="False" DataKeyNames="SwotItemID" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1" OnRowCommand="GridViewStrength_RowCommand"
Width="100%" onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ItemDesc" HeaderText="Item Description" SortExpression="ItemDesc">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Like" InsertVisible="False" SortExpression="Vote">
<ItemTemplate>
<asp:Button ID="Btn_thumbs_up" runat="server" Text = "Like"
CommandName="VoteUp" CommandArgument='<%# Bind("SwotItemID") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dislike" InsertVisible="False" SortExpression="Vote">
<ItemTemplate>
<asp:Button ID="Btn_thumbs_down" runat="server" Text = "Dislike"
CommandName="VoteDown" CommandArgument='<%# Bind("SwotItemID") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
I think you should be able to do this with a foreach loop. You can do something like..
string vote;
//Your connection string. You don't want to open and close within the foreach because it will open and close for each row. Not ideal
conn.Open();
foreach(GridViewRow gvr in GridView1.Rows)
{
//you'll want to find the buttons
Button voteUp = ((Button)gvr.FindControl("Btn_thumbs_up"));
Button voteDown = ((Button)gvr.FindControl("Btn_thumbs_down"));
Label SwotItemID = ((Label)gvr.FindControl("SwotItemID));//I would add SwotItemID as a templatefield with an asp label in it in your gridview
SqlCommand cmdSelectVote= new SqlCommand("SELECT ThumpUpColumn FROM tLoveOrHateTable WHERE SwotItemID = '" + SwotItemID + "'", conn);
vote = Convert.ToString(cmdSelectVote.ExecuteScalar());
if(vote == "0")
{
voteDown.Enabled = false;
}
else if (vote == "1")
{
voteUp.Enabled = true;
}
}
conn.Close();
I would have then on page load or a button or something. Whatever populates your data. This is what I would try first then go from there. So what's it is doing it is running that sql statement for each row. If it's a 0, then it disables the thumbs down button. If it is a 1 then it will disable the thumbs up button. It will go row by row, so if you have 1000 rows(I don't imagine that you do) then it could slow things down. Don't hold me that it will work right away as I have not tested it and I wrote it with in the box. Hope this helps!
I have a gridview which is totatly bounded by programatically .And i added a command field for selection .But it shows up on the first column .Bu i want to change its order to the last column. I tried to use Displayindex , but that column doesn't involve a headerrow.
Here is my gridview looks like
UserID UserName UserAddress
-------------------------------------------------
Select 1 testname testaddress
I just want to pass Select to the last column
UserID UserName UserAddress
-------------------------------------------------
1 testname testaddress Select
<asp:GridView ID="GridForUnits" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Style="text-align: left" Width="851px" OnRowDataBound="GridForUnits_RowDataBound"
OnSelectedIndexChanged="GridForUnits_SelectedIndexChanged1">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
Any Help Appreciate.
Thanks
I would recomend to not auto generate the columns, fill them manually, and then change the visible index of all of them , setting the select button the last one.
More explanation here
Other solution: move the TableCells around in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
List<TableCell> cells = new List<TableCell>();
foreach (DataControlField column in GridView1.Columns)
{
// Retrieve first cell
TableCell cell = row.Cells[0];
// Remove cell
row.Cells.Remove(cell);
// Add cell to list
cells.Add(cell);
}
// Add cells
row.Cells.AddRange(cells.ToArray());
}
Link to source
I have the following piece of code. I did not define any boundfields in my gridview. I am retrieving data using sql queries in my aspx.cs file instead. Is it possible to adjust the width of each column 0, 1, 2? Are there any ways that I can look into? I have tried a lot of ways but it is still not working. Please help!
<asp:GridView ID="surgicalGridView" runat="server"
CaptionAlign="Top" HorizontalAlign="Justify"
DataKeyNames="id" onselectedindexchanged="surgicalGridView_SelectedIndexChanged"
ToolTip="Excel File Download Tool" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="854px">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Download"
ControlStyle-ForeColor="Blue">
<ControlStyle ForeColor="Blue"></ControlStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<br />
You can do that on the OnRowDataBound event of the gridview.
protected void surgicalGridView_RowDataBound(object o, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Width = new Unit("200px");
e.Row.Cells[1].Width = new Unit("400px");
// and so on
}
}
Add this to your Gridview Markup
<asp:GridView ...............................
onrowdatabound="surgicalGridView_RowDataBound"> // just add this event and execute the above code
</asp:GridView>
My solution is below. I have a grid that has 2 defined columns and the rest are bound dynamically. I don't know why setting the column with (e.Row.Cells[0].Width = new Unit("200px");) didn't work, but I found an alternative. Also, my grid has sorting enabled, therefore the linkbutton code.
const int FirstControl = 0;
const int GriDefinedFieldsCount = 2;
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
int col = 0;
foreach (DataColumn dc in SiteManager.Reports.ReportData.Columns)
{
if (dc.ColumnName == "Notes")
{
LinkButton lnk = (e.Row.Cells[col + GriDefinedFieldsCount].Controls[FirstControl] as LinkButton);
lnk.Width = Unit.Pixel(300);
}
col += 1;
}
}
As grid is rendered as table tr and dt so you can use the css class for the grid.
There you can set the width of your columns.
In classes your can use like td, td+td,td+td+td etc
According to the post
.NET Gridview themes examples
Check out these links.
http://icant.co.uk/csstablegallery/index.php?css=69#r69
http://mattberseth2.com/demo/ has lot of gridview customizations with code download.
Paging
Paging With Slider
Sorting with sort icons
Some more themes
http://mattberseth2.com/demo/Default.aspx?Name=A+YUI+DataTable+Styled+GridView&Filter=All
http://mattberseth.com/blog/2007/11/5_gridview_themes_based_on_goo.html
(source: mattberseth.com)