With this site, I am attempting to insert a row in a database through a selection on a gridview row. I've got everything working well except for collecting the primary key from the gridview. I've tried all I can find to no avail. I'm not great with this language as of yet, but my code is below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sdsMicrosoftDB"].ConnectionString;
OleDbConnection currentConnection = new OleDbConnection(connectionString);
string eventID = GridView1.SelectedValue.ToString();
try
{
string eid = Session["eid"].ToString();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO tblVolunteerRoster (eventID,empID) VALUES (#eventID,#empID)";
cmd.CommandType = CommandType.Text;
cmd.Connection = currentConnection;
cmd.Parameters.AddWithValue("#eventID", eventID);
cmd.Parameters.AddWithValue("#empID", eid);
currentConnection.Open();
cmd.ExecuteNonQuery();
}
The code specific to that gridview is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" CellPadding="4" ForeColor="#333333"
GridLines="None" HorizontalAlign="Center"
onrowcommand="GridView1_RowCommand" DataKeyNames="eventID" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField ApplyFormatInEditMode="True" DataField="eventID"
HeaderText="Event ID" SortExpression="eventID" />
<asp:BoundField DataField="eventStartDate" HeaderText="Start Date"
SortExpression="eventStartDate" DataFormatString="{0:MMM dd yyyy}"
ApplyFormatInEditMode="True" />
<asp:BoundField DataField="eventDescription" HeaderText="Description"
SortExpression="eventDescription" />
<asp:BoundField DataField="eventEstHours" HeaderText="Est. Hours"
SortExpression="eventEstHours" />
<asp:BoundField DataField="eventLocation" HeaderText="Location"
SortExpression="eventLocation" />
<asp:BoundField DataField="eventWorkersNeeded" HeaderText="Workers Needed"
SortExpression="eventWorkersNeeded" />
</Columns>
</asp:GridView>
Any ideas? I've beat my head against a wall trying to figure it out on my own. Thanks in advance!
If you want to get the datakeyname
int index = Convert.ToInt32(e.CommandArgument);
string eventID = GridView1.DataKeys[index].Value.ToString()
Related
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();
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[rowIndex];
row.Cells[1].Text = "ACCEPTED";
string msg = "ACCEPTED";
Session["c_email"] = row.Cells[4].Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string insert = "insert into Status values(#email,#c_email,#status)";
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#c_email", Session["c_email"].ToString());
cmd.Parameters.AddWithValue("#email", Session["mechanic"].ToString());
cmd.Parameters.AddWithValue("#status", msg.ToString());
cmd.ExecuteNonQuery();
Label1.Text = "You need to reach the customer within one hour and provide the needful service.";
con.Close();
}
I have been trying to solve this error but couldn't do so. The string is not in correct format, this error is popping. But what could be the solution? I have tried a several ways like "int.Parse", "Int32.TryParse" and also I added e.CommandArgument.ToString()
But all was just of no use. Please help me out with this error.
Thanking you with anticipation.
.aspx code:
<asp:GridView ID="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand"
CssClass="table-bordered table-hover table-responsive table"
BackColor="White" BorderColor="White" CellPadding="3"
DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnpreview" runat="server" Text="Accept" CommandName="Accept" />
<asp:Button ID="btnselect" runat="server" Text="Reject" CommandName="Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Status" />
<asp:BoundField DataField="first_name" HeaderText="First name" SortExpression="first_name" />
<asp:BoundField DataField="last_name" HeaderText="Last name" SortExpression="last_name" />
Change Accept button to-
<asp:Button ID="btnpreview" runat="server" Text="Accept" CommandName="Accept" CommandArgument='<%# Container.DataItemIndex%>' />
Note CommandArgument='<%# Container.DataItemIndex%>' in above line, this will give you index of row.
OR
You can change your code behind to-
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;
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>
I have a gridview populated by some text elements. I am asking the user to put a rate from 1 to 5. I will like to display the rate in the gridview like this ex.: if the user select 4 then in the gridview field it will be display as 4/5. I stored the rate 4 in a database field as a INT.
Here is the code behind
SqlConnection con = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString);
//======= Insert Query.
string cmdText = "INSERT INTO Comments VALUES (#comment,#user,#rate, #date)";
SqlCommand cmd = new SqlCommand(cmdText, con);
//===== Adding parameters/Values.
cmd.Parameters.AddWithValue("#comment", txtComment.Text);
cmd.Parameters.AddWithValue("#user", txtSignature.Text);
cmd.Parameters.AddWithValue("#rate", lstbxRating.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int nbrRecords = cmd.ExecuteNonQuery();
con.Close();
if (nbrRecords >= 1)
{
GridView1.DataBind();
}
}
the code .aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="comment" HeaderText="comment" ReadOnly="True"
SortExpression="comment" />
<asp:BoundField DataField="user" HeaderText="user" ReadOnly="True"
SortExpression="usager" />
<asp:BoundField DataField="rate" HeaderText="rate" ReadOnly="True" SortExpression="rate"
/>
<asp:BoundField DataField="date" HeaderText="date" ReadOnly="True" SortExpression="date"
/>
</Columns>
</asp:GridView>
In the column property of GridView.
Put
DataFormatString="{0:0/5}"
In the field for rate.
Further more. If you can put the html markup of
<app:GridView..........>
I can show you where to add this code.
Just replace your aspx code with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="LinqDataSource1">
<Columns>
<asp:BoundField DataField="comment" HeaderText="comment" ReadOnly="True"
SortExpression="comment" />
<asp:BoundField DataField="user" HeaderText="user" ReadOnly="True"
SortExpression="usager" />
<asp:BoundField DataField="rate" HeaderText="rate" ReadOnly="True" SortExpression="rate" DataFormatString="{0:0/5}"
/>
<asp:BoundField DataField="date" HeaderText="date" ReadOnly="True" SortExpression="date"
/>
it will work, I already tested and it is working fine.
I don't need to use a Gridview if it's not the proper way to do this, some have told me to use a Repeater but I don't know how. Assistance needed!
Looks like this right now:
I want to separate it out by location (a column in the sql table):
ASPX
<asp:GridView runat="server" ID="ReportGrid" CssClass="table" AutoGenerateColumns="False"
AllowPaging="True" BorderColor="#E8CC6B" BorderStyle="Solid" BorderWidth="1px"
Width="100%" OnRowDataBound="ReportGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Owes" HeaderText="Owes" />
<asp:BoundField DataField="Paid" HeaderText="Paid" />
<asp:BoundField DataField="OrigAmt" HeaderText="Amt" />
<asp:BoundField DataField="SubmitDate" DataFormatString="{0:MM/dd/yy}" HeaderText="Date" />
</Columns>
</asp:GridView>
ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
public void bindGridView()
{
string connStr = "";
SqlConnection mySQLconnection = new SqlConnection(connStr);
if (mySQLconnection.State == ConnectionState.Closed)
{
mySQLconnection.Open();
}
SqlCommand mySqlCommand = new SqlCommand(#"SELECT CASE Location
WHEN 1 then 'North'
WHEN 2 then 'South'
WHEN 4 then 'East'
WHEN 5 then 'West'
end as Locations, Name, Owes, Paid, OrigAmt, SubmitDate FROM Cure ", mySQLconnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
ReportGrid.DataSource = myDataSet;
ReportGrid.DataBind();
if (mySQLconnection.State == ConnectionState.Open)
{
mySQLconnection.Close();
}
}
protected void ReportGrid_RowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[3].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
}
Try adding a Locations column to your GridView control like this:
<asp:GridView runat="server" ID="ReportGrid" CssClass="table" AutoGenerateColumns="False"
AllowPaging="True" BorderColor="#E8CC6B" BorderStyle="Solid" BorderWidth="1px"
Width="100%" OnRowDataBound="ReportGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Locations" HeaderText="Location" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Owes" HeaderText="Owes" />
<asp:BoundField DataField="Paid" HeaderText="Paid" />
<asp:BoundField DataField="OrigAmt" HeaderText="Amt" />
<asp:BoundField DataField="SubmitDate" DataFormatString="{0:MM/dd/yy}" HeaderText="Date" />
</Columns>
</asp:GridView>
There is no need to use an ASP.NET repeater if you add a bound field column to your GridView. Hope this helps.