Display Multiple Images in a gridview - c#

I want to display multiple images in a gridview within a single row at a time.
Also I want to make sure that for multiple images uploaded at a time there should be only one row gets inserted into the table.
See my BindGrid() code;-
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, gallery_id, image_title, image_description, image_path from tbl_gallery_stack order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdGalleryData.DataSource = dt;
grdGalleryData.DataBind();
}
}
}
}
Also see the HTML for gridview:-
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="10"
OnPageIndexChanging="grdGalleryData_PageIndexChanging"
CssClass="hoverTable"
DataKeyNames="Id">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="gallery_id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_title" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_description" HeaderText="Gallery Description" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Getimage(Eval("image_path").ToString()) %>' Width="100px" Height="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

I propose to you visit web site : https://social.msdn.microsoft.com/Forums/windowsapps/en-US/0565b55e-3daf-4eef-85ac-a8ab72af4e68/displaying-the-images-into-the-gridview / regularly !

It seems you are querying the data as row-per-image instead of row-with -related-images. So you need to change the database query pattern to something like below (Its just for demonstration purpose to hold nested dataset):
void BindGrid()
{
using (SqlConnection con = new SqlConnection("YOUR CONNECTION STRING"))
{
using (SqlDataAdapter personAdapter = new SqlDataAdapter("SELECT * FROM PersonTable", con))
using (SqlDataAdapter personImagesAdapter = new SqlDataAdapter("SELECT * FROM PersonImages", con))
{
DataSet dataSet = new DataSet("PersonAndImagesDataSet");
personAdapter.Fill(dataSet, "PersonTable");
personImagesAdapter.Fill(dataSet, "PersonImages");
DataRelation personWithImages = dataSet.Relations.Add("PersonAndImages", dataSet.Tables["PersonTable"].Columns["Id"],
dataSet.Tables["PersonImages"].Columns["Person_Id"]);
if (grdGalleryData.DataSource == null)
{
grdGalleryData.DataSource = dataSet.Tables["PersonTable"];
grdGalleryData.DataBind();
}
}
}
}
In the HTML you can include a ListView (or a control of your choice to hold list items) and on GridView's databind event do something like this:
ASPX View
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="3"
CssClass="hoverTable"
DataKeyNames="Id" OnRowDataBound="grdGalleryData_RowDataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="Name" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ListView runat="server" ID="lvImages" OnDataBinding="lvImages_DataBinding" >
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Eval("ImagePath")%>' Width="50px" Height="50px" />
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Databinding to ListView (C#)
protected void grdGalleryData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var personId = Convert.ToInt32((e.Row.DataItem as DataRowView)["Id"]);
var imageListView = e.Row.FindControl("lvImages") as ListView;
//Just for demo purpose. Get only required image data based on the parent table id in actual code.
if (data == null)
{
data = GetData();
}
//In below line, based on the parent table id , get the image data from data store. Just for brevity I am querying a complete dataset on every row data bind.
//E.g: var resultRows = DataStore.GetImage(int personId); and bind this to ListView directly.
var resultRows = data.Tables["PersonImages"].AsEnumerable().Where(img => img.Field<int>("Person_Id") == personId);
DataTable dtImages = new DataTable();
if (resultRows != null && resultRows.Count()>0)
dtImages = resultRows.CopyToDataTable();
imageListView.DataSource = dtImages; //Here you should be assigning result table/collection that you get from data store.
imageListView.DataBind();
}
}
Hope this help you.

Related

Checkbox select row(s) from one GridView (Table) to another back and forth

I have two gridviews each with their own table.
I'm trying to make it so I can select a row(s) from GridViewA and move it to GridViewB (not copy). Then be able to move the selected row(s) from GridViewB back to GridViewA.
GridViewA (populated with SqlDataSource1)
<asp:GridView ID="grdA" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="white" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
GridViewB (populated with SqlDataSource2)
<asp:GridView ID="grdB" runat="server" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" DataKeyNames="ID" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="Vertical" Width="75%">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="Data1"HtmlEncode="false"/>
<asp:BoundField DataField="Data2" HtmlEncode="false"/>
<asp:BoundField DataField="Data3" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBox2" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
Button to move row(s) from GridViewA to GridViewB. It works but I'm not sure how to delete the row from GridViewA after moving to GridViewB
protected void btnSubmit_Click(object sender, EventArgs e)
{
string DataA, DataB, DataC;
var connectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
var insertStatement = "INSERT INTO SqlTableB (Data1, Data2, Data3) VALUES (#Data1, Data2, Data3)";
using (var sqlConnection = new SqlConnection(connectionString))
foreach (GridViewRow gRow in grdA.Rows)
{
CheckBox cb = (gRow.FindControl("chkBox") as CheckBox);
if (cb.Checked)
{
DataA = Convert.ToString(gRow.Cells[1].Text);
DataB = Convert.ToString(gRow.Cells[2].Text);
DataC = Convert.ToString(gRow.Cells[3].Text);
using (var sqlCommand = new SqlCommand(insertStatement, sqlConnection))
{
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Data1", DataA);
sqlCommand.Parameters.AddWithValue("#Data2", DataB);
sqlCommand.Parameters.AddWithValue("#Data3", DataC);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
}
}
Please let me know if I can make the issue more clear, thank you
I would approach the problem this way:
First, make sure you set the PK row id for the Grid (that way you dont have to include in the display, or markup).
So USE "datakeys" setting of the grid - this will help a lot.
So, say two grids, like this:
<div style="float:left;width: 40%">
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveRight" runat="server" Text="Move->" style="float:right" CssClass="btn" OnClick="cmdMoveRight_Click" />
</div>
<div style="float:left;width: 40%;margin-left:10px">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" cssclass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" SortExpression="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdMoveMoveLeft" runat="server" Text="<-Move" CssClass="btn" OnClick="cmdMoveMoveLeft_Click" />
</div>
Code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrids();
}
}
void LoadGrids()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * from tblHotelsA");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
cmdSQL.CommandText = "SELECT * from tblHotelsB";
GridView2.DataSource = MyRstP(cmdSQL);
GridView2.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
Ok, so now we have this:
Ok, now a button to move right, and one to move left. Code is:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsB (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsA " +
"WHERE tblHotelsA.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsA WHERE ID = #ID";
MoveRows(GridView1,strSQL,strSQLDel);
}
protected void cmdMoveMoveLeft_Click(object sender, EventArgs e)
{
// move records right A to table B
string strSQL =
"INSERT INTO tblHotelsA (FirstName, LastName, HotelName, Description) " +
"SELECT FirstName, LastName, HotelName, Description FROM tblHotelsB " +
"WHERE tblHotelsB.id = #ID";
string strSQLDel = "DELETE FROM tblHotelsB WHERE ID = #ID";
MoveRows(GridView2, strSQL,strSQLDel);
}
void MoveRows(GridView gv,string strSQL, string strSQLDel)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
// delte the row
cmdSQL.CommandText = strSQLDel;
SqlRun(cmdSQL);
}
}
// now re-load both grids to reflect changes
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}

asp.net gridview sum and quantity of the columns

i have a small problem with summarizing of the total value of the columns. I have a shopping cart where i want to summarize quantity and price of the item. I've done summarize of prices but when i was trying to multiply it to quantity it didn't work.
.
Could you please give me an advice.
Here is a gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="id" ShowFooter="true" ShowHeaderWhenEmpty="true">
<Columns>
<asp:BoundField DataField="item" HeaderText="Item" SortExpression="item"></asp:BoundField>
<asp:BoundField DataField="BEE" HeaderText="Description" SortExpression="BEE"></asp:BoundField>
<asp:BoundField DataField="count" HeaderText="Quantity" SortExpression="count"></asp:BoundField>
<asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"></asp:BoundField>
<asp:TemplateField>
<FooterTemplate>
<asp:Label ID="lbltxtTotal" runat="server" Text="Total Price" />
</FooterTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"></asp:BoundField>
<asp:ButtonField CommandName="Delete" Text="Delete" ButtonType="Button" ShowHeader="True" HeaderText="Delete"></asp:ButtonField>
</Columns>
<EmptyDataTemplate>No Record Available</EmptyDataTemplate>
<FooterStyle BackColor="White" Font-Bold="True"></FooterStyle>
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Right" BackColor="White" ForeColor="Black"></PagerStyle>
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#F7F7F7"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#4B4B4B"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#E5E5E5"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#242121"></SortedDescendingHeaderStyle>
</asp:GridView>
and here is a backend:
protected void Timer1_Tick(object sender, EventArgs e)
{
string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
string Username_new = Username.Replace("APAC\\", "");
GridView1.DataBind();
//live data
String myquery = "Select * from Basket where Username='" + Username_new + "'";
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.FooterRow.Cells[1].Text = "Total Amount";
GridView1.FooterRow.Cells[2].Text = dt.Compute("Sum(price)", "").ToString();
}
This is easy.
Add method to your code:
protected void getSUM()
{
// SQL query that gets total of product sales where category id = 1
string SqlQuery = #"SELECT SUM(ProductSales) AS TotalSales
FROM [NORTHWIND].[dbo].[Sales by Category]
WHERE CategoryID = 1";
// Declare and open a connection to database
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ConnectionString);
conn.Open();
// Creates SqlCommand object
SqlCommand comm = new SqlCommand(SqlQuery, conn);
// Gets total sales
decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());
// Close connection
conn.Close();
conn.Dispose();
comm.Dispose();
// Adds formatted output to GridView footer
GridView1.Columns[1].FooterText = String.Format("{0:c}", TotalSales);
}
In markup code, we'll define footer template and call getSUM method:
<FooterTemplate>
Total sales: <%# getSUM(); %>
</FooterTemplate>

“Input string was not in a correct format” error

I have a code for Updating the Row in a gridview, but the issue is that, when I edit and update the Row it is giving me error as Input string was not in a correct format. At the below line of Code:-
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active);
Please see my code for your reference:-
<asp:GridView ID="grdPostData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;"
CellPadding="3" AutoGenerateColumns="False" AllowPaging="true" PageSize="4" CssClass="hoverTable"
OnPageIndexChanging="grdPostData_PageIndexChanging" OnRowEditing="grdPostData_RowEditing"
OnRowDataBound="grdPostData_RowDataBound" DataKeyNames="Id" OnRowCommand="grdPostData_RowCommand" OnRowUpdating="grdPostData_RowUpdating">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30"
ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Post Category" ItemStyle-Width="50">
<ItemTemplate>
<asp:DropDownList ID="ddlPostCategory" AppendDataBoundItems="true" runat="server"
AutoPostBack="false">
<%-- <asp:ListItem Text="Select" Value="0"></asp:ListItem>--%>
</asp:DropDownList>
</ItemTemplate>
<ItemStyle Width="50px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td">
<ControlStyle CssClass="k-grid td"></ControlStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" CommandName="eDelete" CommandArgument='<%# Bind("Id") %>' ImageUrl="~/images/delete.png"
runat="server" Width="15px" Height="15px" CausesValidation="False"
OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
<HeaderStyle Width="15%"></HeaderStyle>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" CausesValidation="false"
ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png"
UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
<ItemStyle Width="15px"></ItemStyle>
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
No Result Found
</EmptyDataTemplate>
</asp:GridView>
Also see the CS code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
//getting key value, row id
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
//get all the row field detail here by replacing id's in FindControl("")..
GridViewRow row = grdPostData.Rows[e.RowIndex];
string PostTitle = ((TextBox)(row.Cells[0].Controls[0])).Text;
string Postdesc = ((TextBox)(row.Cells[1].Controls[0])).Text;
// string ddlPostCategory = ((DropDownList)(row.Cells[2].Controls[0])).SelectedValue;
string Active = ((TextBox)(row.Cells[3].Controls[0])).Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = Id;
cmd.Parameters.Add("#title", SqlDbType.NVarChar, 155).Value = PostTitle;
cmd.Parameters.Add("#description", SqlDbType.NVarChar, 99999999).Value = Postdesc;
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active);
cmd.Connection = conn;
conn.Open();
IsUpdated = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
if (IsUpdated)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrposts.aspx';", true);
BindGrid();
}
else
{
//Error while updating details
grdPostData.EditIndex = -1;
//bind gridview here..
//GET GDATA FROM DATABASE AND BIND TO GRID VIEW
}
}
I know this is not worth a question, tried but couldn't find. Please help.
Code for Dropdownlist aspx:-
<div class="controls">
<asp:DropDownList ID="ddlActiveInactive" CssClass="selectpicker form-control-drp wd"
runat="server" Style="width: 100%" ValidationGroup="AddNew">
<asp:ListItem Value="1" Text="Active"></asp:ListItem>
<asp:ListItem Value="0" Text="InActive"></asp:ListItem>
</asp:DropDownList>
</div>
It is a dropdownlist which has values Active and InActive
If you actually want to get the DropDownList's selected value use FindControl:
var ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
int active = -1; // or whatever
if(ddlActive.SelectedValue != "")
active = int.Parse(ddlActive.SelectedValue);
// ...
cmd.Parameters.Add("#Active", SqlDbType.Int)
.Value = active != -1 ? active : System.Data.SqlTypes.SqlInt32.Null;
Use trim() function to remove the whitespaces and the convert it to int.
cmd.Parameters.Add("#Active", SqlDbType.Int).Value = Convert.ToInt32(Active.Trim());

Trying to add a second level nested table without sucess

I am trying to learn how to add an additional nested table inside the firstLevelGrid but I am not succeding. Any help would be appreciated.
Particularly I am doing something wrong in managing the OnRowDataBound when I create the second level grid, both in the markup and the code behind.
This is the code I have that generate the grid and the first level. I have not added my attempts for the second level grid just to avoid to mess up the code.
It is not homework, I am not a professional coder and I am a selflearner.
<div>
<asp:GridView ID="zeroLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="Code" OnRowDataBound="OnRowDataBoundZeroLevel">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="firstLevelPanel" runat="server" Style="display: none">
<asp:GridView ID="firstLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<!-- Here is where I add the second level grid copying the entire block "TemplateFiled" of the firstLevelGrid and renaming it secondLevel...-->
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Code" HeaderText="Code" />
<asp:BoundField ItemStyle-Width="150px" DataField="Description" HeaderText="Description" />
<asp:BoundField ItemStyle-Width="150px" DataField="Quantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
and my c# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
zeroLevelGrid.DataSource = GetData("select top 10 * from Table_xx");//top10 only for test purposes
zeroLevelGrid.DataBind();
}
}
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["Test1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBoundZeroLevel(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string code = zeroLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView firstLevelGrid = e.Row.FindControl("firstLevelGrid") as GridView;
firstLevelGrid.DataSource = GetData(string.Format("IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')) SELECT * from [{0}]", code));
firstLevelGrid.DataBind();
}
}
//here is where I add an OnRowDataBound event copying the above one as OnRowDataBoundFirstLevel
//but then I get lost...
}
I would be glad if someone could indicate me how to add an additional level of nested grid inside the firstLevelGrid identical to it. I would be happy to offer a bounty to get this right but unfortunatelly I do not have enough rep yet. Thank you a lot.
Similart to your firstLevelGrid, you have to declare the third level grid inside the firstLevelGrid as a template column
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="secondLevelGrid" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<%--Your columns go here--%>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
Then handle OnRowDataBound event for the firstLevelGrid
OnRowDataBound="firstLevelGrid_OnRowDataBound"
In the RowDataBound event you can get the grid view, data key and bind the child grid
protected void firstLevelGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView firstLevelGrid = e.Row.NamingContainer as GridView;
string code = firstLevelGrid.DataKeys[e.Row.RowIndex].Value.ToString();
GridView secondLevelGridView = e.Row.FindControl("secondLevelGrid") as GridView;
secondLevelGridView.DataSource = //GetData
secondLevelGridView.DataBind();
}
}

Dynamically display images in a grid view based on the column values in asp.net

I am databinding the table To grid view, I want to add a column status in the table and the values in the column will be message sent or message saved. I want to display images based on the value is message send or saved. How can I do that dynamically.
DataTable dt = new DataTable();
try
{
string MysqlStatement = "SELECT MsgID, MsgText, RespondBy, ExpiresBy, OwnerName FROM tbl_message WHERE tbl_user_tbl_organisation_OrganisationID = #Value1";
MySqlCommand sqlCmd = new MySqlCommand(MysqlStatement, connectionString);
sqlCmd.Parameters.AddWithValue("#Value1", newOrgID);
MySqlDataAdapter sqlDa = new MySqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Grid_Messagetable.DataSource = dt;
Grid_Messagetable.DataBind();
Grid_Messagetable.Columns[2].Visible = false;
}
else
{
}
<asp:GridView ID="Grid_Messagetable" runat="server" AllowPaging="True" SelectedIndex="0"
DataKeyNames="MsgID" ShowHeaderWhenEmpty="True" OnRowDeleting="MsgTable_RowDeleting"
OnRowEditing="MsgTable_RowEditing" AutoGenerateColumns="False" BorderStyle="Double"
Width="537px">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" HeaderText="Edit controls"
ButtonType="Image" DeleteImageUrl="~/Styles/Images/Delete.gif" EditImageUrl="~/Styles/Images/Edit.gif" />
<asp:TemplateField HeaderText="DashBoard">
<ItemTemplate>
<asp:ImageButton ID="imgbtn_ViewDashBoard" ImageUrl="Styles/Images/dash.png" Enabled="True"
Width="50" runat="server" PostBackUrl='<%# Eval("MsgID", "ResponseMetric.aspx?MsgID={0}") %>'
Text='Send'></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="MsgID" HeaderText="MsgID" ReadOnly="True" SortExpression="MsgID" />
<asp:BoundField DataField="MsgText" HeaderText="MsgText" ReadOnly="True" SortExpression="MsgText" />
<asp:BoundField DataField="RespondBy" HeaderText="RespondBy" ReadOnly="True" SortExpression="RespondBy" />
<asp:BoundField DataField="ExpiresBy" HeaderText="ExpiresBy" ReadOnly="True" SortExpression="ExpiresBy" />
<asp:BoundField DataField="OwnerName" HeaderText="OwnerName" ReadOnly="True" SortExpression="OwnerName" />
<asp:ImageField DataImageUrlField="Sent" HeaderText="Status"
NullImageUrl="~/Styles/Images/White.gif">
</asp:ImageField>
</Columns>
</asp:GridView>
You can create template column field like this:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:ImageButton ID="img" runat="server" ImageUrl='<%# (Eval("Status") == "Sent") ? "messagesent.png" : "messagesaved.png" %>' />
</ItemTemplate>
</asp:TemplateField>

Categories

Resources