I am trying to get the StudentFirstName from data base and show in the text box right now am using grid view where it shows the data but not in textbox am not sure how to get all the data from data base and show in individual text box.
MyDB
StudentFirstName SchoolID StudCourse
abc sc123 A
cef sc155 A
gij sc133 A
abc sc122 B
cef sc156 B
gij sc144 B
C#
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select StudentFirstName from student WHERE StudCourse=#DDSelected_Class order by StudentFirstName ASC";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#DDSelected_Class", DDSelected_Class);
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader == null || !oReader.HasRows)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);
}
else
{
while (oReader.Read())
{
GridView1.DataSource = oReader;
GridView1.DataBind();
}
}
myConnection.Close();
}
}
Gridview
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
You will need to define ItemTemplate for your column. It will contain a textbox and the field name name in Eval to bind it.
Complete code sample:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("StudentFirstName ") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<Columns>
</asp:GridView>
Related
I am having difficulty in displaying the dynamic data into text-boxes. I am in a situation where I have multiple text-boxes and I want to fetch value from table where column name is 'registration_charges' and 'amount'. Now column registration_charges' contains data e.g., 'OPD_CHARGES', 'DR.Charges' and 'amount' column has data e.g.,:- 5000, 1000. I want to display amount in text box accordingly.
<asp:Label runat="server" >OPD Ch.</asp:Label>
<asp:TextBox ID="txtopd_charges" runat="server" Width="100px"
style="text-
align: right;float:right;margin-right:15px;">/-</asp:TextBox>
<asp:Label runat="server" >DR Ch.</asp:Label>
<asp:TextBox ID="txtdr_charges" runat="server" Width="100px"
style="text-
align: right;float:right;margin-right:15px;">/-</asp:TextBox>
Back-end code:
//connection code
con.Open();
SqlCommand cmd = new SqlCommand("SELECT amount FROM
Mst_Charges WHERE registration_charges IN('OPD_CHARGES',
DR.Charges')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
txtopd_charges.Text = ???
txtdr_charges.Text = ???
}
else
{
}
}
catch (Exception ex)
{
}
}
In your query you must select registration_charges along with the amount
SqlCommand cmd = new SqlCommand("SELECT amount,registration_charges FROM
Mst_Charges WHERE registration_charges IN('OPD_CHARGES',
DR.Charges')", con);
You can fetch data of your DataTable like this:
txtopd_charges.Text = dt.Rows[0]["amount"].ToString();
txtdr_charges.Text = dt.Rows[0]["registration_charges"].ToString();
UPDATED
You can bind the data with Repeater and initialized your textbox inside of the ItemTemplate which will repeat your data exist in DataTable.
Aspx Code
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:TextBox ID="txtopd_charges" Text='<%# Eval("amount") %>' runat="server"></asp:TextBox>
<asp:TextBox ID="txtdr_charges" Text='<%# Eval("registration_charges") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
and in your C#
if (dt.Rows.Count > 0)
{
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
I currently have two dropdown lists and they are populated with names from a database. What I want to do is have a player be selected, and then on a button click, the data from the table is populated into a gridview. Right now I am just getting a "No data returned" message and I cannot figure out why.
<asp:DropDownList ID="ddl_QB1" runat="server" Width="200px" AppendDataBoundItems="True"
AutoPostBack="True" Height="16px" DataTextField="Player" DataValueField="id" ></asp:DropDownList>
<asp:Gridview ID="GridView1" runat="server" AutoGenerateColumns="false" Visible="true"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px"
CellPadding="4" GridLines="Horizontal" ShowHeaderWhenEmpty="True" EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Total Points">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("[Pts]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Pts") %>'>
</asp:Label>
</ItemTemplate>
protected void Page_Load(object sender, EventArgs e)
{
LoadQuarterbacks();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] from Quarterbacks", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddl_QB1.DataSource = dt;
ddl_QB1.DataBind();
}
}
private void LoadQuarterbacks()
{
ddl_QB1.Items.Clear();
ddl_QB2.Items.Clear();
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("SELECT id, Player FROM Quarterbacks", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("Quarterbacks");
da.Fill(ds); // fill dataset
ddl_QB1.DataTextField = ds.Tables[0].Columns["Player"].ToString(); // text field name of table dispalyed in dropdown
ddl_QB2.DataTextField = ds.Tables[0].Columns["Player"].ToString();
ddl_QB1.DataValueField = ds.Tables[0].Columns["id"].ToString();
ddl_QB2.DataValueField = ds.Tables[0].Columns["id"].ToString(); // to retrive specific textfield name
ddl_QB1.DataSource = ds.Tables[0];
ddl_QB2.DataSource = ds.Tables[0];
ddl_QB2.DataBind();//assigning datasource to the dropdownlist
ddl_QB1.DataBind(); //binding dropdownlist
con.Close();
ddl_QB1.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
ddl_QB2.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionstring);
string query = "SELECT [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] FROM Quarterbacks where id=" + ddl_QB1.SelectedValue;
SqlDataAdapter sda = new SqlDataAdapter(query,con);
con.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Following 3 changes would give desired results.
First - AutoPostBack should be set to false on the dropdown element as that is causing postback even before you click on the button.
Second - remove the current code inside if(!Page.IsPostback). This code is not necessary. Also, this code is not setting DataTextField and DataValueField properties for ddl_QB1 and ddl_QB2.
Third - put the method call LoadQuarterbacks() inside if(!Page.IsPostback). We do not have to bind these values for ddl_QB1 and ddl_QB2 on each request.
If a refresh is required on the dropdown controls, then call LoadQuarterbacks() method after binding the gridview at the end of the button click. That way you are capturing the selected values from dropdown before rebinding the them. Rebinding the DropDowns would cause them loose the selected values.
I have a RadGrid and a RadComboBox outside of RadGrid (say comboOutside), inside a Web Form.
Inside RadGrid, there is 1 more RadComboBox (say comboRadGrid). On selection of items from comboOutside, comboRadGrid is bind i.e., If item 'Company' is selected from comboOutside, then all the company names will be bind in comboRadGrid; and then user select specific company from comboRadGrid and records are added in RadGrid.
For all items, functionality is working fine but I am facing issue in binding of a specific comboOutside item.
i.e., When I choose a specific item from comboOutside, say I have 100 items inside comboOutside, and when I select 35th items from it, then comboRadGrid always throw this error while binding records for 35th item (since 35th item has 2000+ records to bind in comboRadGrid)
Error is below:
Funcitonality is working fine for all the items except 1 specific item of RadComboBox. I don't understand why. Due to this I am unable to add records in RadGrid
Below is my code-
C# code
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
//code to bind inside RadComboBox list
RadComboBox rcb = (RadComboBox)item.FindControl("ddlAccountCode");
rcb.DataSource = GetAccCode(CompanyCode);
rcb.DataTextField = "AccountDescription";
rcb.DataValueField = "AccountCodeID";
rcb.DataBind();
rcb.Items.Insert(0, new RadComboBoxItem("- Select -", string.Empty));
Session["AccCode"] = rcb.SelectedValue.ToString();
string a = rcb.SelectedValue.ToString();
//Select particular dropdown value while "Edit"
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
rcb.SelectedValue = lblAcCode2.Text;
rcb.SelectedItem.Text = lblAcCode2.Text;
}
}
}
//code to bind outside RadComboBox list
protected void BindComapnyDL()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = dt;
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
string a = ddlCompany.SelectedValue.ToString();
}
//RadComboBox select index changed event
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedValue == null || ddlCompany.SelectedValue == "")
{
GridCommandItem cmditem = (GridCommandItem)RGGSTAcCode.MasterTableView.GetItems(GridItemType.CommandItem)[0];
System.Web.UI.WebControls.Button ctrl = (System.Web.UI.WebControls.Button)cmditem.FindControl("AddNewRecordButton");
ctrl.Enabled = false;
System.Web.UI.WebControls.LinkButton btn = (System.Web.UI.WebControls.LinkButton)cmditem.FindControl("InitInsertButton");
btn.Enabled = false;
string content = "Please select company first";
ScriptManager.RegisterStartupScript(this, typeof(string), "Successful", "alert('" + content + "');", true);
}
else
{
RGGSTAcCode.Rebind();
}
}
HTML code
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false"
Filter="Contains" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true"
DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true" EmptyDataText="No record available."
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource="RGGSTAcCode_NeedDataSource" OnItemDataBound="RGGSTAcCode_ItemDataBound"
OnInsertCommand="RGGSTAcCode_InsertCommand" OnDeleteCommand="RGGSTAcCode_DeleteCommand"
OnUpdateCommand="RGGSTAcCode_UpdateCommand" OnItemCommand="RGGSTAcCode_ItemCommand">
<mastertableview ShowHeadersWhenNoRecords="true" autogeneratecolumns="false" datakeynames="AccountCodeID" InsertItemDisplay="Top"
insertitempageindexaction="ShowItemOnCurrentPage" ShowFooter="True" CommandItemDisplay="Top" ClientIDMode="Static">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240"
DropDownWidth="310" HighlightTemplatedItems="true" CausesValidation="true"
Filter="Contains" AppendDataBoundItems="true" DataTextField="AccountDescription" DataValueField="AccountCodeID">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="AccountDescription" HeaderText="Description" UniqueName="AccountDescription" SortExpression="AccountDescription" InsertVisiblityMode="AlwaysHidden" ReadOnly="true" ></telerik:GridBoundColumn>
<telerik:GridBoundColumn aggregate="SUM" DataField="Amount" HeaderText="Amount" FooterAggregateFormatString="Total : {0:###,##0.00}" DataFormatString="{0:n}" FooterStyle-BackColor="#ffc04c" UniqueName="Amount" SortExpression="Amount"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Remark" HeaderText="IFCA Remark" UniqueName="Remark" SortExpression="Remark">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn ConfirmTextFormatString="Are you sure you want to Delete {0} Account Code?" ConfirmTextFields="AccountCodeID"
ConfirmDialogType="RadWindow" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn"></telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<CommandItemSettings AddNewRecordText="Add new record" RefreshText="Refresh"></CommandItemSettings>
</mastertableview>
</telerik:RadGrid>
Please let me know why this error is coming for a specific item of RadComboBox selection.
Used LoadOnDemand mechanish, by following this link: demos.telerik.com/aspnet-ajax/combobox/examples/…
This approach is used for large number of records to be bind in RadComboBox which will avoid such exceptions to occur. And its working fine. Thank you #Icemanind for the help.
How can I render links in columns of WebForms GridView?
I have the following code
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.UsersContacts WHERE UserId='vika'", con);
con.Open();
var list1 = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var node = reader[1];
list1.Add(node.ToString());
}
}
con.Close();
GridView1.DataSource = list1;
GridView1.DataBind();
and I want to do something such as list1.Add("<a href='#'>"+node.ToString()+"<a>"); and make it a link in my GridView.
I would rather do this at the gridview template definition instead of passing the link from the datasource. Your gridview definition can have the asp:HyperLinkField or asp:HyperLink field and bind the data as required.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:HyperLinkField
HeaderText="View Details"
DataNavigateUrlFields="node"
DataNavigateUrlFormatString="~/TargetPage.aspx?Id={0}"
DataTextField="node"
/>
</Columns>
</asp:GridView>
Or
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("node", "~/TargetPage.aspx?Id={0}") %>' Text="View Details" />
I have a gridview which contains textboxes and dropdowns.In gvScheduleBattingScore_RowDataBound Event I am binding dropdowns without any problem. The button control is outside to the gridview. I actually want to submit all the textbox values and dropdown selected values to the database on buttonclickevent But I don't know where I am going wrong.
The Problem is Textboxes do not contain any text and am getting Exception
Input string was not in a correct format.
Please help me out...
<asp:GridView ID="gvScheduleBattingScore" runat="server" AllowSorting="false" AutoGenerateColumns="False" AllowPaging="false"
GridLines="None" CellPadding="1" CssClass="GridViewStyle" ShowFooter="false" width="100%"
OnRowDataBound="gvScheduleBattingScore_RowDataBound">
<Columns>
<asp:BoundField DataField="P_PlayerId" HeaderText="Player Id" HeaderStyle-Wrap="true" HeaderStyle-Width="5%" Visible="false"/>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" HeaderStyle-Wrap="true" HeaderStyle-Width="30%"/>
<asp:TemplateField HeaderText="Playing Order" HeaderStyle-Wrap="true" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtPlayingOrder" runat="server" CssClass="TinyTexBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bold By">
<ItemTemplate>
<asp:DropDownList ID="ddlBoldBy" runat="server"> </asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</br>
<asp:Button ID="ButtonAdd" runat="server" Text="Add" CssClass="SmallButton"
ValidationGroup="Add" onclick="ButtonAdd_Click"/>
On ButtonClick Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlConnection dBConnection = null;
try
{
int playerId;
short plyerOrder;
string BatsmanStatus;
int boldBy;
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["CriConn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_InsertScores", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow GVRow in gvScheduleBattingScore.Rows)
{
string textPlayerId = GVRow.Cells[0].Text;
TextBox textPlyerOrder = (TextBox)GVRow.Cells[1].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = GVRow.Cells[2].FindControl("txtStatus") as TextBox;
DropDownList DropDownBoldBy = (DropDownList)GVRow.Cells[18].FindControl("ddlBoldBy");
playerId = Convert.ToInt32(textPlayerId );
if (!string.IsNullOrEmpty(textPlyerOrder.Text))
plyerOrder = Convert.ToInt16(textPlyerOrder.Text);
if (!string.IsNullOrEmpty(textBatsmanStatus.Text))
BatsmanStatus = textBatsmanStatus.Text;
if (!string.IsNullOrEmpty(DropDownBoldBy.SelectedValue) && DropDownLbwBy.SelectedValue != "Select")
boldBy = Convert.ToInt32(DropDownBoldBy.SelectedValue);
cmd.Parameters.Add("#PlayerId", SqlDbType.NVarChar).Value = playerId;
cmd.Parameters.Add("#PlayerId", SqlDbType.Int).Value = playerId;
cmd.Parameters.Add("#plyerOrder", SqlDbType.Int).Value = plyerOrder;
cmd.Parameters.Add("#BatsmanStatus", SqlDbType.NVarChar).Value = BatsmanStatus;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
cmd.ExecuteNonQuery();
dBConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}
As per the Chat discussion with #bhoopendra.sahoo, we come to the conclusion that it is a Binding issue.
When Button Click Event is fired, the GridView binds again causing the issue.
The fix is to bind the GridView only once and restrict its binding during other events.
Add a null checking before converting the textbox value to int
if (!string.IsNullOrEmpty(textPlayerId.Text))
playerId = Convert.ToInt32(textPlayerId);
Also make these changes to you code, to find the textbox controls in the correct cell
TextBox textPlyerOrder = (TextBox)GVRow.Cells[2].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = (TextBox)GVRow.Cells[3].FindControl("txtStatus");