How to delete a row from DB (*.mdb) in c# - c#

I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!

Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.

Related

Can't get the grid view data and store it to database

<div class="container">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Size="Medium">
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Width="80px" Text='<%#Eval("studentID") %>'/>
</ItemTemplate>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton runat="server" OnCommand="LinkButton_Click" Text=" VoteCandidate"> </asp:LinkButton>
</ItemTemplate>
</asp:GridView>
<div>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</div>
</div>
Here is my form to show the gridview.
protected void loadCandidate()
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select studentID from candidate where faculty='FOCS'", con);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void LinkButton_Click(Object sender, EventArgs e)
{
String MyConnection2 = "Server=localhost;database=ovs;Uid=root;password=; Convert Zero Datetime=True";
foreach (GridViewRow g1 in GridView1.Rows)
{
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
String query = "insert into voting (studentID)values ('" + g1.Cells[0].Text + "')" ;
MySqlCommand MyCommand2 = new MySqlCommand(query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MyConn2.Close();
}
}
When I execute the sql insert command, no error occur, but I expect the studentID that displayed in the gridview being stored in the voting table, but the studentID on the voting table are empty.
Since you use a template field in your GridView, you can't use the cell directly, you need to look for the label inside the cell like this:
foreach (GridViewRow g1 in GridView1.Rows)
{
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
}
But if you using the loop the way you do it right now, there will be an insert for every row in the GridView, not only for the one you clicked on...
If you want to get the Id for the row the LinkButton is in, don't iterate over the rows. Instead use the NamingContainer-property of the sender like this:
LinkButton linkButton = (LinkButton)sender;
GridViewRow g1 = (GridViewRow)linkButton.NamingContainer;
Label lblStudentId = (Label)g1.Cells[0].FindControl("lblID");
string studentId = lblStudentId.Text;
// now proceed with your inserting.
For more details look at this question and answer

Object reference not set to an instance of an object. want to select all columns of the row button clicked on gridview

All I want to do is when A user clicks on "See more" button on gridview, He will get all the columns of the row button clicked on detailView1.. But I dont know where Im going wrong. Im working on C# asp.net
Can anyone help? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
DetailsView1.Visible = false;
SqlCommand cmd1 = new SqlCommand("SELECT cars.carid, cars.make, cars.model, cars.condition, cars.amount, img.img FROM cars INNER JOIN img ON cars.carid = img.carid ", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Clicked(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
foreach (GridViewRow row in this.GridView1.Rows)
{
Label lblshow = (Label)GridView1.Rows[row.RowIndex].FindControl("carid");
SqlCommand cmd1 = new SqlCommand("Select * from cars where carid='" + lblshow.Text + "'", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
DetailsView1.DataSource = dt;
DetailsView1.DataBind();
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" Width="1000px" AllowPaging="True" PageSize="8" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle><PagerStyle CssClass="pgr"></PagerStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Select</HeaderTemplate>
<ItemTemplate>
<asp:Button runat="server" Text="See more" OnClick="Button2_Clicked" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Image</HeaderTemplate>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("img") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("img")) : string.Empty %>' alt="image" height="100" width="150"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
IsPostback on the page load event. Hope your problem get resolved.

how to bind two columns of a database table up and down as a single column in data gridview

how to bind two columns of a database table UP and DOWN as a single column in data gridview.
Kindly help me.
.ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<span>Merged cell</span>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblMergedField" runat="server" Text='<%# Eval("ID") + " - " + Eval("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void BindData()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT ID,City FROM Cities", con))
{
using (var adapter = new SqlDataAdapter(command))
{
con.Open();
var table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
con.Close();
}
}
}
}
Output:

How to use the checkboxs in gridview?

I have a asp.net form displaying the user details from an Oracle database, using a grid-view. I even managed to get a check-box field in the grid-view using the following template..
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chck"/>
</ItemTemplate>
</asp:TemplateField>
I want the admin to be able to select multiple entries using the check-boxes and perform a certain action on them. I tried using, for the delete operation, the following
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (Convert.ToBoolean(GridView1.Rows[i].Cells[1].Value == true))
GridView1.Rows.RemoveAt[i];
}
However, this shows an error. Apparently, each check-box on each row must have its own unique index. How do I get to it?
Any sort of help will be appreciated. Thanx :)
You need to find control inside your gridview row using findControl
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb1 = (CheckBox)GridView1.Rows[i].FindControls("chck");
if(cb1.Checked)
GridView1.Rows.RemoveAt[i];
}
Use find control to get checkboxes:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chck = (CheckBox)GridView1.Rows[i].FindControl("chck");
if (chck != null)
{
if (chck.Checked)
{
GridView1.Rows.RemoveAt[i];
}
}
}
This is Aspx FIle :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
</asp:GridView>
This is CS File :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = #"SELECT CategoryID, CategoryName, Approved FROM Categories";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}
public void chkStatus_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
string cid = row.Cells[1].Text;
bool status = chkStatus.Checked;
string constr = #"Server=.\SQLEXPRESS;Database=TestDB;uid=waqas;pwd=sql;";
string query = "UPDATE Categories SET Approved = #Approved WHERE CategoryID = #CategoryID";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#Approved", SqlDbType.Bit).Value = status;
com.Parameters.Add("#CategoryID", SqlDbType.Int).Value = cid;
con.Open();
com.ExecuteNonQuery();
con.Close();
LoadData();
}

Gridview inside Datalist ASP.NET

I am trying to place an asp gridview inside an asp datalist. For each item in the datalist I would like certain values from another database table to be returned.
I have written the following code, but the gridview returns not data (I can confirm there is records in the database and the stored procedure is correct). The asp datalist is working fine.
What am I doing wrong that is not populating the gridview?
<asp:DataList runat="server" id="listResponses" DataKeyField="QuestionID" CssClass="confirm" OnItemDataBound="listResponses_ItemDataBound">
<ItemTemplate>
<h3 class="confirm new">Question <asp:Label ID="lblaOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label></h3>
<div class="confirm_question">
<asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label>
<p class="confirm"><%# DataBinder.Eval(Container.DataItem, "QuestionText") %></p>
</div> <!-- end confirm_question -->
<asp:GridView runat="server" ID="gridResponses" DataKeyNames="QuestionID"">
<Columns>
<asp:BoundField DataField="AnswerTitle" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="Responses" HeaderText="Response Count" HeaderStyle-Width="150px" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:DataList>
And here is the code behind.
public partial class questionnaire_responses : System.Web.UI.Page
{
OsqarSQL GetData;
DataTable DT;
private string _productConnectionString;
private SqlConnection _productConn;
protected void Page_Load(object sender, EventArgs e)
{
string questionnaireId = Session["qID"].ToString();
int qid = Convert.ToInt32(questionnaireId);
GetData = new OsqarSQL();
string name = GetData.GetQuestionnaireName(qid);
lblQuestionnaireName.Text = name;
if (!IsPostBack)
{
DT = GetData.GetQuestionNameDataList(qid);
listResponses.DataSource = DT;
listResponses.DataBind();
}
}
private void BindGrid(GridView GridView, int questionId)
{
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
GridView.DataBind();
}
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses=(GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex]);
}
}
//Method from the data access class
public DataTable GetAnswerTitle(int QuestionId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetAnswer", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
,yCommand.Parameters.Add(new SqlParameter("#QUESTION_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = QuestionId;
return createDataTable(getData(myCommand));
}
You've created an empty DataTable as DataSource for your GridView.
Replace
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
with this
DataTable dt = GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;

Categories

Resources