I have a gridview set in ASP.Net that has a name and a checkbox.
<h4>Current Instructor</h4>
<div class="hide-overflow">
<asp:GridView runat="server" ID="GridViewInstructor" DataSourceID="SqlDataSourceInstructor" AutoGenerateColumns="false" CssClass="table table-bordered table-striped" ShowHeader="false" EmptyDataText="No Instructor associated to class." DataKeyNames="Instructor">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CBInstructorPrimary" runat="server" Checked='<%#Eval("Primary")%>' OnCheckedChanged="PrimaryUpdate" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="InstructorName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSourceInstructor" DataSourceMode="DataReader" ConnectionString="<%$ ConnectionStrings:HRAgriConnectionString %>"
SelectCommand="
SELECT a.Primary, a.ClassID, a.Instructor, b.LName + ', ' + b.FName as InstructorName
FROM tblClass a
LEFT JOIN tblUser b
ON a.Instructor = b.UserName
WHERE a.ClassID = #classID
ORDER BY a.Primary DESC">
<SelectParameters>
<asp:QueryStringParameter Name="classID" QueryStringField="cid" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
This makes a gridview table that looks like
my c# code behind looks like this
protected void PrimaryUpdate(object sender, EventArgs e)
{
//CheckBox activeCheckBox = sender as CheckBox;
//foreach (GridViewRow rw in GridViewInstructor.Rows)
//{
// CheckBox chkBx = (CheckBox)rw.FindControl("CBInstructorPrimary");
// if (chkBx != activeCheckBox)
// {
// chkBx.Checked = false;
// }
// else
// {
// chkBx.Checked = true;
// }
//}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "UPDATE tblClass SET [Primary] = #Primary WHERE classID=#classID and Instructor = #InstructorName";
cmd.Connection = con;
con.Open();
foreach (GridViewRow row in GridViewInstructor.Rows)
{
//Get Instructor Name.
string InstructorName = row.Cells[0].Text;
//Get the Class Id from the DataKey property.
classID = Request.QueryString["cid"];
//Get the checked value of the CheckBox.
bool Primary = (row.FindControl("CBInstructorPrimary") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#InstructorName", InstructorName);
cmd.Parameters.AddWithValue("#classID", classID);
cmd.Parameters.AddWithValue("#Primary", Primary);
cmd.ExecuteNonQuery();
}
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
The outcome should be if you check another checkbox it will update the Primary field (which is a bit field) to 1 if checked and all others in that group will be set to 0. And only 1 checkbox can be checked at a time. I know I have commented out the top part for now. I just haven't been able to figure out how to get this working.
Related
<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
I have a GridView that is populated from an SqlDataSource with specific values.
How would I add a default row to the top of myGridView?
And I want the the default row to have text 'All'
<asp:GridView ID="gvPoints"
runat="server"
DataSourceID="SqlDataSource_userPoints"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="id_point,title"
BorderWidth="0px"
Width="100%"
GridLines="None">
<Columns>
<asp:ButtonField
CommandName="selectedPoint"
DataTextField="title"
ButtonType="Link" />
</Columns>
<RowStyle HorizontalAlign="Left"></RowStyle>
</asp:GridView>
<asp:SqlDataSource
ID="SqlDataSource_userPoints"
runat="server"
ConnectionString='<%$ ConnectionStrings:TipTourConnectionString %>'
SelectCommand ="SELECT
id_point,
title,
body
FROM tt_point
WHERE id_user = #id_user">
<SelectParameters>
<asp:QueryStringParameter
QueryStringField="id_user"
DefaultValue="0"
Name="id_user">
</asp:QueryStringParameter>
</SelectParameters>
</asp:SqlDataSource>
I think the easiest way in this scenario would be to add it with the SQL statement.
This assumes id_point is a numeric field. If not, remove the convert function
SELECT 'All' AS id_point, 'All' AS title, 'All' AS body
UNION
SELECT CONVERT(varchar, id_point), title, body FROM tt_point WHERE id_user = #id_user
Replace This
<asp:ButtonField CommandName="selectedPoint" DataTextField="title" ButtonType="Link" />
with this
<asp:ButtonField CommandName="selectedPoint" DataTextField="title" ButtonType="Link" HeaderText="All" />
I added HeaderText="All" to your ButtonField
Make sure in your gridview this is there ShowHeader="true"
If you want to add 2 rows bind your gridview like this
strcon = "data source=.\\SQLEXPRESS;database=testDB;trusted_Connection=yes";
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT id_point,title,body FROM tt_point WHERE id_user = #id_user", connection);
string userid = "0";
command.Parameters.AddWithValue("#id_user", userid);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
DataRow dr = dt.NewRow();
dr["id_point"] = "All";
dr["title"] = "All";
dr["body"] = "All";
dt.Rows.InsertAt(dr, 0);
DataRow dr1 = dt.NewRow();
dr1["id_point"] = "All";
dr1["title"] = "All";
dr1["body"] = "All";
dt.Rows.InsertAt(dr1, 1);
gvPoints.DataSource = dt;
gvPoints.DataBind();
}
call this method on page load like this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
Here in strcon database name is testDB replace with your databasename
Remove this from gridview DataSourceID="SqlDataSource_userPoints"
I have a Gridview on which I have Edit option for editing the Row. I have written the code for Edit and Update but it is not getting updated and the row gets blank. I debugged the code and didn't got to know what was the exact problem. Please see the code for your ref and let me know what is the exact issue:-
Gridview aspx code:
<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" OnRowDataBound="grdPostData_RowDataBound"
OnRowDeleting="grdPostData_RowDeleting" DataKeyNames="Id" OnRowEditing="grdPostData_RowEditing" OnRowUpdating="grdPostData_RowUpdating"
OnRowCancelingEdit="grdPostData_RowCancelingEdit" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="title" HeaderText="Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:BoundField DataField="description" HeaderText="Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<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>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("Id") %>' > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
</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];
// DropDownList ddlPostlistcategory = ((DropDownList)(row.Cells[0].Controls[0]));
TextBox txtPostTitle = ((TextBox)(row.Cells[0].Controls[0]));
TextBox txtPostdesc = ((TextBox)(row.Cells[1].Controls[0]));
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_Post SET title=#title, description=#description, active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
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..
grdPostData.DataBind();
}
}
protected void grdPostData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdPostData.EditIndex = -1;
BindGrid();
}
Edited part of the code:-
protected void grdPostData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool IsUpdated = false;
int Id = Convert.ToInt32(grdPostData.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = grdPostData.Rows[e.RowIndex];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory");
//TextBox title = ((TextBox)(row.Cells[0].Controls[0]));
//TextBox description = ((TextBox)(row.Cells[1].Controls[0]));
TextBox title = (TextBox)row.FindControl("txtPostTitle");
TextBox description = (TextBox)row.FindControl("txtPostdesc");
DropDownList ddlActive = (DropDownList)row.FindControl("ddlActiveInactive");
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "UPDATE tbl_Pages SET page_title=#page_title,page_description=#page_description,meta_title=#meta_title,meta_keywords=#meta_keywords,meta_description=#meta_description,Active=#Active WHERE Id=#Id";
cmd.CommandText = "UPDATE tbl_post SET title=#title,description=#description,active=#active WHERE Id=#Id";
cmd.Parameters.AddWithValue("#Id", Id);
cmd.Parameters.AddWithValue("#title", txtPostTitle.Text);
cmd.Parameters.AddWithValue("#description", txtPostdesc.Text);
cmd.Parameters.AddWithValue("#active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
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
{
grdPostData.EditIndex = -1;
grdPostData.DataBind();
}
}
Code Is perfect just small mistake.
Change
TextBox ddlActive = ((TextBox)(row.Cells[2].Controls[0]));
To
TextBox ddlActive = ((TextBox)(row.Cells[3].Controls[0]));
You want to set value of Active which is 3rd control not 2nd.
If Your control is in TemplateField then you have find control from row
For DropDownList You need to try something like this:
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
Following Line will generate error
cmd.Parameters.AddWithValue("#Active", Convert.ToInt32(ddlActiveInactive.SelectedValue));
You need to find this control ddlActiveInactive from grid which you are missing
Don't Use AddWithValue it gives Unexpected Results Sometimes
SOURCE
EDIT:
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];
DropDownList ddlPostCategory = (DropDownList)row.FindControl("ddlPostCategory") ;
string PostTitle = row.Cells[0].Text;
string Postdesc = row.Cells[1].Text;
string Active = row.Cells[2].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.Varchar,100).Value=PostTitle ;
cmd.Parameters.Add("#description",SqlDbType.Varchar,200).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 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();
}
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.